07 # 手写 find 方法

简介: 07 # 手写 find 方法

find 的使用

find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

  • ele:表示数组中的每一个元素
  • index:表示数据中元素的索引
  • array:表示数组
<script>
    var arr = [1, 3, 5, 7, 9];
    var result = arr.find(function (ele, index, array) {
        console.log("ele----->", ele);
        console.log("index----->", index);
        console.log("array----->", array);
        return ele > 6;
    });
    console.warn("result----->", result);
</script>

手写实现 find 方法

<script>
    Array.prototype.kaimoFind = function (fn) {
        for (let i = 0; i < this.length; i++) {
            // fn 是 kaimoFind 中传递的参数,是一个函数,this 是 arr
            let res = fn(this[i], i, this);
            if (res) {
                return this[i];
            }
        }
    };
    var result2 = arr.kaimoFind(function (ele, index, array) {
        console.log("ele---kaimoFind-->", ele);
        console.log("index---kaimoFind-->", index);
        console.log("array---kaimoFind-->", array);
        return ele > 6;
    });
    console.warn("result2---kaimoFind-->", result2);
</script>



目录
相关文章
|
5月前
13 # 手写 concat 方法
13 # 手写 concat 方法
28 0
|
5月前
03 # 手写 call
03 # 手写 call
21 0
|
4月前
|
人工智能 JavaScript 前端开发
让OpenAi给我写个JS的set对象的笔记和快速去重方法
让OpenAi给我写个JS的set对象的笔记和快速去重方法
21 0
|
4月前
vector删除的简洁写法
vector删除的简洁写法
|
5月前
|
索引
08 # 手写 filter 方法
08 # 手写 filter 方法
23 0
|
5月前
|
索引
06 # 手写 map 方法
06 # 手写 map 方法
22 0
|
应用服务中间件 Apache nginx
Yii框架中的'enablePrettyUrl' => true, 这段代码是干什么的?底层原理是什么?为什么这样写?
Yii框架中的'enablePrettyUrl' => true, 这段代码是干什么的?底层原理是什么?为什么这样写?
119 0
手写系列 # 3:实现 call 方法
手写系列 # 3:实现 call 方法
43 0
手写系列 # 3:实现 call 方法
|
前端开发
react实战笔记16:数组方法补充fliter和find
react实战笔记16:数组方法补充fliter和find
58 0
react实战笔记16:数组方法补充fliter和find
|
索引
从underscore源码看如何实现map函数
经常会看到这样的面试题,让面试者手动实现一个 map 函数之类的,嗯,貌似并没有什么实际意义。但是对于知识探索的步伐不能停止,现在就来分析下如何实现 map 函数。
73 0
从underscore源码看如何实现map函数