js 实现.find
实现数组的 .find 方法
JavaScript 的 .find 方法用于查找数组中第一个满足条件的元素。如果找不到,返回 undefined。以下是几种实现方式:
原生方法
直接使用原生 Array.prototype.find:
const array = [1, 2, 3, 4, 5];
const result = array.find(item => item > 3);
console.log(result); // 输出: 4
手动实现
通过循环遍历数组实现:
function find(array, callback) {
for (let i = 0; i < array.length; i++) {
if (callback(array[i], i, array)) {
return array[i];
}
}
return undefined;
}
// 使用示例
const array = [1, 2, 3, 4, 5];
const result = find(array, item => item > 3);
console.log(result); // 输出: 4
实现原理
- 遍历数组的每个元素。
- 对每个元素执行回调函数,传入当前元素、索引和原数组。
- 如果回调函数返回
true,返回当前元素并停止遍历。 - 如果遍历结束仍未找到,返回
undefined。
支持 thisArg
原生 find 方法支持传入 thisArg 作为回调函数的 this 值。以下是支持 thisArg 的实现:
function find(array, callback, thisArg) {
const boundCallback = thisArg ? callback.bind(thisArg) : callback;
for (let i = 0; i < array.length; i++) {
if (boundCallback(array[i], i, array)) {
return array[i];
}
}
return undefined;
}
// 使用示例
const array = [1, 2, 3, 4, 5];
const context = { threshold: 3 };
const result = find(
array,
function(item) { return item > this.threshold; },
context
);
console.log(result); // 输出: 4
注意事项
- 回调函数应返回布尔值,否则可能导致意外行为。
- 原生
find方法在稀疏数组中会跳过空位。 - 手动实现时需确保正确处理边界条件,如空数组或无效回调。






