JavaScript30-7 数组的一些基本方法

本次来学习数组的一些方法,之前学习的js数组的方法是在第四课里面(没有写到随笔里面)

之前第四课主要讲的是 filter() ,map() 这次课程主要介绍的是 some()`、`every()`、`find()`、`splice()`、`slice()`.

之后会总结一篇关于数组的文章。


some()

some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。

some() 方法会依次执行数组的每个元素:

  • 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
  • 如果没有满足条件的元素,则返回false。

注意: some() 不会对空数组进行检测。

注意: some() 不会改变原始数组。

来看看代码示例

const people = [
      { name: 'Wes', year: 1988 },
      { name: 'Kait', year: 1986 },
      { name: 'Irv', year: 1970 },
      { name: 'Lux', year: 2015 }
    ];

    const comments = [
      { text: 'Love this!', id: 523423 },
      { text: 'Super good', id: 823423 },
      { text: 'You are the best', id: 2039842 },
      { text: 'Ramen is my fav food ever', id: 123523 },
      { text: 'Nice Nice Nice!', id: 542328 }
    ];

 数据上,给了两组数据来作为测试数据。

例如,我们想知道  是否有人超过 19 岁? 

这个时候可以使用some()

es6


const isAdult = people.some( person => {
		const currentYear = (new Date()).getFullYear();
		return currentYear - person.year >= 19;
	});


es5

const isAult = people.some(function(person) { const jinnian = (new Date()).getFullYear();//今年 if( jinnian - person.year >19 ) return true; });

every()

every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)。

every() 方法使用指定函数检测数组中的所有元素:

  • 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
  • 如果所有元素都满足条件,则返回 true。

注意: every() 不会对空数组进行检测。

注意: every() 不会改变原始数组。

那么对于这样的条件下,我们就可以使用 every 了 

 是否所有人都是成年人?

    const allAdult = people.every( person => new Date().getFullYear() - person.year >= 19);
 const allAdult = people.every(function(person){

      if( new Date().getFullYear() - person.year ){
        return true;
      }
    });

根据以上数据来看结果确实是true

find() 

find() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素。

find() 方法为数组中的每个元素都调用一次函数执行:

  • 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。 
  • 如果没有符合条件的元素返回 undefined 

注意: find() 对于空数组,函数是不会执行的。

注意: find() 并没有改变数组的原始值。

现在有这样一个条件:找到 ID 号为 823423 的评论

这个时候,我们就可以使用find来查找了。

    const comment = comments.find(comment => comment.id == 823423);

findIndex()

findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。

findIndex() 方法为数组中的每个元素都调用一次函数执行:

  • 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。 
  • 如果没有符合条件的元素返回 -1

注意: findIndex() 对于空数组,函数是不会执行的。

注意: findIndex() 并没有改变数组的原始值

splice()

splice() 方法用于插入、删除或替换数组的元素。

注意:这种方法会改变原始数组!。

slice()

slice() 方法可从已有的数组中返回选定的元素。

slice()方法可提取字符串的某个部分,并以新的字符串返回被提取的部分。

注意: slice() 方法不会改变原始数组。

使用以上三种方法,就可以实现对某条数据的查找和删除啦!

例如我们要删除ID 号为 823423 的评论

const index = comments.findIndex(comment => comment.id == 823423);

首先我们找到她的index

之后可以使用

comments.splice(index, 1);

来删除

也可以使用

const newComments = [
        ...comments.slice(0, index),
        ...comments.slice(index + 1)
    ];

来删除

总之array还有许多方法。大家可以去查阅官方的文档或者直接百度就好啦

原文地址:https://www.cnblogs.com/Let7/p/7716578.html