2020-09-05 18:54:07
在 JavaScript 中,find() 方法用于查找数组中第一个满足条件的元素,若无匹配项则返回 undefined。 以下是详细说明与使用示例:
核心特性通过对象属性或组合条件筛选:
const users = [ { name: '态搭Alice', age: 25 }, { name: 'Bob', age: 35 }, { name: 'Charlie', age: 40 }];// 查找第一个年龄>30的用户const firstOver30 = users.find(user => user.age > 30);console.log(firstOver30); // 输出: { name: 'Bob', age: 35 }// 多条件组合:年龄>30且名字包含'B'const specificUser = users.find(user => user.age > 30 &&败纤 user.name.includes('B'));console.log(specificUser); // 输出: { name: 'Bob', age: 35 }与 findIndex()、filter() 的对比findIndex()返回匹配元素的索引,未找到返回 -1:
const index = arr.findIndex(element => element > 25);console.log(index); // 输出: 2(30的索引)filter()返回所有匹配元素的新数组,适合需要全部结果的场景:
const allOver30 = users.filter(user => user.age > 30);console.log(allOver30); // 输出: [{ name: 'Bob', age: 35 }, { name: 'Charlie', age: 40 }]空数组:始终返回 undefined。
const emptyArr = [];console.log(emptyArr.find(x => x > 10)); // 输出: undefined旧浏览器兼容性:通过 Polyfill 实现:
if (!Array.prototype.find) { Array.prototype.find = function(callback) { if (this == null) throw new TypeError('Array.prototype.find called on null or undefined'); if (typeof callback !== 'function') throw new TypeError('callback must be a function'); const list = Object(this); const length = list.length >>> 0; for (let i = 0; i < length; i++) { if (callback.call(arguments[1], list[i], i, list)) return list[i]; } return undefined; };}find() 更简洁且不易出错,避免手动控制循环终止:
// for循环实现相同功能let result;for (let i = 0; i < arr.length; i++) { if (arr[i] > 25) { result = arr[i]; break; }}console.log(result); // 输出: 30总结通过合理运用 find(),可显著提升代码可读性与执行效率。