12 # 手写 findIndex 方法

简介: 12 # 手写 findIndex 方法

findIndex 的使用

findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。

<script>
    var arr = [1, 3, 5, 7, 8];
    var result = arr.findIndex(function (ele, index, array) {
        console.log("ele----->", ele);
        console.log("index----->", index);
        console.log("array----->", array);
        return ele > 5;
    });
    console.warn("result----->", result);
</script>


手写 findIndex

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


如果条件改成大于50,找不到就返回 -1



目录
相关文章
|
7月前
|
前端开发
Promise的用法&原理&手写实现-2
Promise的用法&原理&手写实现-2
21 1
|
7月前
01 # 手写 new 的原理
01 # 手写 new 的原理
25 0
|
5月前
|
索引
09 # 手写 some 方法
09 # 手写 some 方法
14 0
|
5月前
|
索引
10 # 手写 every 方法
10 # 手写 every 方法
21 0
|
7月前
|
前端开发 JavaScript API
Promise的用法&原理&手写实现-1
Promise的用法&原理&手写实现-1
25 0
|
9月前
|
设计模式 Java Spring
用300行代码手写1个Spring框架,麻雀虽小五脏俱全
为了解析方便,我们用application.properties来代替application.xml文件,具体配置内容如下:
28 0
|
10月前
|
前端开发 算法 安全
前端面试100道手写题(1)—— 手写Promise实现
今年的金三银四面试,遇到了很多新的面试八股文,其实心里对手写题或者算法题有一定抵触,因为实际工作中基本上就不会用到这些东西,但是正因为这些基础八股文,才能真正验证一个人对技术有多热爱的程度。也有可能近几年没有对这些基础知识进行巩固,所以干脆一狠心,先立个flag, 准备完成100道手写题。
205 0
|
11月前
|
设计模式 前端开发 Java
手写模拟SpringMvc源码
手写模拟SpringMvc源码
|
12月前
|
缓存 前端开发 API
手写中实现并学习ahooks——useRequest
最近业务没有之前紧张了,也是消失了一段时间,也总结了一些之前业务上的问题。 和同事沟通也是发现普通的async + await + 封装api在复杂业务场景下针对于请求的业务逻辑比较多,也是推荐我去学习一波ahooks,由于问题起源于请求,因此作者也是直接从 useRequest 开始看起。
106 1
|
设计模式 JavaScript 前端开发
手写简易版的curry
手写简易版的curry
90 0