1.find的用法
菜鸟教程:
find() 方法返回通过测试(函数内判断)的数组的第一个元素。
find() 方法为数组中的每个元素都调用一次函数行:当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行数。
如果没有符合条件的元素返回 undefined
注意: find() 对于空数组,函数是不会执行的。返值为undefined
注意: find() 并没有改变数组的原始值。
find有两个参数,第一个参数是应当返回boolean的判断函数,第二个参数用于给判断函数绑定this
2.find使用示例
//找出id等于3的元素
const arr = [
{id:1,name:'小明'},
{id:2,name:'小红'},
{id:3,name:'forceddd'},
]
const res = arr.find( item => item.id===3 )
3.find的实现
Array.prototype.myFind = function (cb, thisValue) {
if (cb.constructor !== Function) {
throw new Error(cb + '不是一个函数')
}
//如果不是空数组,遍历数组,依次执行回调函数,一旦回调函数返回值为真,返回此项元素,否则继续执行
if (this.length) {
for (let i = 0; i < this.length; i++) {
//将thisValue绑定成cb的this
if (cb.call(thisValue, this[i], i, this)) return this[i]
}
}
//如果是空数组,不作处理,最终会默认返回undefined
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。