前言
我们知道 find()
方法是 JavaScript 中用于在数组中查找特定条件的第一个元素,如果找到一个元素使得回调函数返回true,则该元素作为结果返回,如果没有找到这样的元素,则返回undefined,该函数不会修改原始数组。这里来记录一下
1. 基本语法
array.find((item,index)=>{
console.log(item,index);
})
array.find(callback(element[, index[, array]])[, thisArg])
2. 参数解释
callback
:必需。要在数组中每个元素上执行的函数。element
:必需。当前正在处理的数组元素。index
:可选。正在处理的元素的索引。array
:可选。调用该方法的数组本身。thisArg
:可选。当执行回调函数时使用的this
值。
3. 回调函数
find()
方法的第一个参数 callback
是一个函数,用于测试每个元素是否符合条件,接收三个参数:
element
:表示当前正在被处理的元素。index
:表示正在被处理的元素的索引。array
:表示当前正在被处理的数组对象。
回调函数应该返回一个布尔值,表示当前元素是否符合我们的条件。如果返回 true
,则会停止遍历并返回该元素的值;否则,继续遍历直到遇到符合条件的元素或者整个数组都被遍历完毕。
4. 使用实例
find()
方法的实际应用,请看
实例 1:查找数组中的第一个负数
const arr = [1, 2, -3, 4, -5];
const negativeNum = arr.find(num => num < 0);
console.log(negativeNum); // 输出:-3
实例 2:从对象数组中查找符合条件的对象
const users = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Charlie'}
];
const user = users.find(u => u.id === 2);
console.log(user); // 输出:{id: 2, name: 'Bob'}
实例 3:使用参数指定回调函数中的 this
值
function isEven(num) { return num % 2 === 0; }
const nums = [1, 3, 4, 7, 8];
const evenNum = nums.find(isEven, this);
console.log(evenNum); // 输出:4
5. 注意事项
find()
方法会遍历整个数组,直到找到满足条件的元素或者遍历完整个数组。- 如果数组为空,那么返回
undefined
。- 在回调函数中修改数组本身不是一个好习惯。如果要修改数组,请使用
map()
或者filter()
方法。- 当多个元素符合条件时,
find()
方法只会返回第一个符合条件的元素。find()
方法是 ES6 中新增的方法,在较旧的浏览器中可能不被支持。