一:概念

find()方法用于查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回undefined

注意:

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

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

二:语法

array.find(function(currentValue, index, arr),thisValue)

参数

callback:必须。为数组中每个元素执行的函数,该函数接受三个参数:
currentValue:必须。数组中正在处理的当前元素。
index:可选。当前元素的索引值。
arr:可选。当前元素所在的数组对象。
thisValue:可选。传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值

三:实例

1、求数组中第一个大于1的值

let arr1 = [1, 2, 3, 4, 5];
let num = arr1.find(item => item > 1);
console.log(num)  //輸出的結果是2

2、提取第一个id为1的对象

 var arr = [{
        id: 1,
        name: '张一',
        age: 25,
        class: '一班'
    }, {
        id: 1,
        name: '张二',
        age: 25,
        class: '二班'
    }, {
        id: 2,
        name: '张三',
        age: 25,
        class: '三班'
    }]
    let obj = arr.find(item => item.id == 1)
    console.log(obj); 
    // 结果:{id: 1, name: '张一', age: 25, class: '一班'}
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐