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
        }
仅为个人理解,如有错谬,欢迎指正。
如果对您有所帮助,请您点个赞吧!

forceddd
271 声望912 粉丝

一名前端爱好者。