手写数组方法(十二):findIndex

372 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第20天,点击查看活动详情

今天带大家来学习下数组的findIndex方法。

语法

array.findIndex(function(item, index, arr), ins);

参数

回调函数

回调函数接收3个参数

  • item: 必需。当前元素
  • index: 可选。当前元素的索引
  • arr: 可选。当前元素所属的数组对象

ins

可选。 传递给回调函数的this指针。 如果这个参数为空,this指针为window

返回值

返回符合测试条件的第一个数组元素索引,如果没有符合条件的则返回 -1

测试

找出列表中第一个大于1的元素,返回其数组下标。很显然,该元素是2,下标为1

let list = [1, 2, 3];
list.findIndex((item => item > 1));

image.png

找出列表中第一个下标大于1的元素的下标?那在这里很显然是2,元素为3findIndex只返回下标,于是返回值为2

let list = [1, 2, 3];
list.findIndex((item, index) => index > 1);

image.png

找出列表中数组元素大于3的,显然在列表中不存在,返回-1

let list = [1, 2, 3];
list.findIndex((item, index, arr) => arr[index] > 3);

image.png

第二个参数指定了回调函数的this指向,如果不传,则默认为全局window

let list = [1, 2, 3];
list.findIndex(function(item, index) { 
    console.log(this);
    return index > 1;
}, {a: 1});
let list = [1, 2, 3];
list.findIndex(function(item, index) { 
    console.log(this);
    return index > 1;
});

image.png

手写

根据以上特性,我们不难写出以下代码:

Array.prototype._findIndex = function(callback, ins) {
    let res = -1;
    for(let i = 0; i < this.length; i++) {
        if(callback.call(ins, this[i], i, this)) {
            res = i;
        }    
    }
    return res;
}

结语

今天关于数组findIndex的介绍就讲到这里,关注我获取更多有关数组方法的讲解,后续会持续更新。我是末世未然,一个爱折腾的新晋奶爸,祝好