js 实现 find 方法
实现基础数组查找功能
通过回调函数匹配数组元素,返回第一个满足条件的元素。若未找到则返回 undefined。
Array.prototype.customFind = function(callback) {
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
return this[i];
}
}
return undefined;
};
使用示例
const numbers = [1, 2, 3, 4];
const found = numbers.customFind(item => item > 2);
console.log(found); // 输出: 3
支持 thisArg 参数
允许通过 thisArg 指定回调函数的 this 上下文。

Array.prototype.customFind = function(callback, thisArg) {
const context = thisArg || undefined;
for (let i = 0; i < this.length; i++) {
if (callback.call(context, this[i], i, this)) {
return this[i];
}
}
return undefined;
};
使用示例
const obj = { threshold: 2 };
const found = [1, 2, 3].customFind(
function(item) { return item > this.threshold; },
obj
);
console.log(found); // 输出: 3
边界条件处理
增加对稀疏数组和非法回调的校验,提升健壮性。

Array.prototype.customFind = function(callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function');
}
const context = thisArg || undefined;
for (let i = 0; i < this.length; i++) {
if (i in this && callback.call(context, this[i], i, this)) {
return this[i];
}
}
return undefined;
};
校验场景
// 稀疏数组
const sparse = [1, , 3];
console.log(sparse.customFind(item => item === undefined)); // undefined
// 非法回调
try {
[1, 2].customFind(null);
} catch (e) {
console.log(e.message); // "Callback must be a function"
}
性能优化建议
对于大型数组,可考虑提前终止循环或使用更高效的遍历方式(如 for-of)。
Array.prototype.customFind = function(callback, thisArg) {
const context = thisArg || undefined;
for (const [index, value] of this.entries()) {
if (callback.call(context, value, index, this)) {
return value;
}
}
return undefined;
};






