es6数组方法

  • find()
  • findIndex()
  • filter()


find()

用法:find详细用法介绍

find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。
find() 方法为数组中的每个元素都调用一次函数执行:
当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
如果没有符合条件的元素返回 undefined
注意: find() 对于空数组,函数是不会执行的。
注意: find() 并没有改变数组的原始值。

:代码在myArr数组中查找元素值大于4的元素,找到后立即返回。返回的结果为查找到的元素:

const array = [1, 2, 3, 4, 5, 6];
const num = array.find(value => value > 4);
console.log(num);// 5

没有符合元素,返回undefined:

const array = [1, 2, 3, 4, 5, 6];
 const num = array.find(value => value > 40);
console.log(num);  //undefined

回调函数有三个参数

  1. value:当前的数组元素
  2. index:当前索引值
  3. arr:被查找的数组
const array = [10, 2, 5, 9, 5, 6];
 const num = array.find((value, index, arr) => {
	 console.log(value, index, arr);
        // 10 0(6)[10, 2, 5, 9, 5, 6]
        //  2 1(6)[10, 2, 5, 9, 5, 6]
        //  5 2(6)[10, 2, 5, 9, 5, 6]
        //  9 3(6)[10, 2, 5, 9, 5, 6]
        //  5 4(6)[10, 2, 5, 9, 5, 6]
        //  6 5(6)[10, 2, 5, 9, 5, 6]
 });

findIndex()

用法:findIndex详细用法介绍

findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
findIndex() 方法为数组中的每个元素都调用一次函数执行:
当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
如果没有符合条件的元素返回 -1
注意: findIndex() 对于空数组,函数是不会执行的。
注意: findIndex() 并没有改变数组的原始值。

与find的相同和不同

相同:

  1. findIndex()与find()的使用方法相同
  2. indIndex()当中的回调函数也是接收三个参数与find()相同

不同:

  1. 如果没有符合条件元素时findIndex()返回的是-1 而find()返回的是undefined

列:

const array = [1, 2, 3, 4, 5, 6];
const num = array.findIndex(value => {
return value == 4
 });
console.log(num);  //3
const array = [1, 2, 3, 4, 5, 6];
const num = array.findIndex(value => value > 40);
console.log(num);  //-1

filter()

用法:filter详细用法介绍

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。

与find和findIndex的相同和不同

相同: filter()与find()使用方法也相同 同样都接收三个参数

不同:

  1. 返回值不同在find()只返回第一个满足条件的元素 filter()返回的是一个满足条件所有的数组
  2. 如果条件不满足 filter()返回的是一个空数组 find条件不满足返回undefined

列:

find方法

const data = [
            {
                name: 'hello12',
                endTime: 1617023820000,
                startTime: 1617023220000,
                timeRange: '21:07 - 21:17',
                errorRate: '1.1822‰',
                pv: 3343680,
                pvError: 3953,

            },
            {
                "items": [{
                    name: '美女1',
                    endTime: 1617023820000,
                    id: '234',
                },
                {
                    name: '美女2',
                    endTime: 1617023820000,
                    id: '234',
                },
                ]
            }
        ]

        const num = data[1].items.find(i => {
            return i.name =='美女1'
        })
        console.log(num) 
        //{name: "美女1", endTime: 1617023820000, id: "234"}

filter方法

es6 查找对象数组中符合条件对象_数组