find方法的原理及实现

8次阅读

共计 722 个字符,预计需要花费 2 分钟才能阅读完成。

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