js 实现 find 方法
实现 Array.prototype.find 方法
JavaScript 的 find 方法用于查找数组中第一个满足条件的元素。如果没有找到符合条件的元素,则返回 undefined。
基本实现
Array.prototype.myFind = function(callback, thisArg) {
for (let i = 0; i < this.length; i++) {
if (callback.call(thisArg, this[i], i, this)) {
return this[i]
}
}
return undefined
}
使用示例
const array = [5, 12, 8, 130, 44]
const found = array.myFind(element => element > 10)
console.log(found) // 12
实现要点
- 遍历数组中的每个元素
- 对每个元素执行回调函数
- 如果回调函数返回
true,立即返回当前元素 - 如果遍历结束没有找到符合条件的元素,返回
undefined - 支持传递
thisArg参数指定回调函数的this值
Polyfill 实现
以下是更完整的 polyfill 实现,包含参数校验:

Array.prototype.myFind = function(callback, thisArg) {
if (this == null) {
throw new TypeError('"this" is null or not defined')
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function')
}
const array = Object(this)
const length = array.length >>> 0
for (let i = 0; i < length; i++) {
if (i in array && callback.call(thisArg, array[i], i, array)) {
return array[i]
}
}
return undefined
}
性能考虑
- 使用
for循环而非forEach以便可以提前返回 - 使用
in操作符检查稀疏数组 - 使用
length >>> 0确保长度为非负整数






