JS中数组的findIndex方法

8,983 阅读1分钟

作用:

在数组中搜索要找的值,返回它的元素位置。

说明:

findIndex() 方法传入的第一个参数是一个函数,并返回传入函数(测试条件)符合的数组的第一个元素的位置。如果找得到则返回位置,找不到则返回 -1 。

第二个参数(可选):为传入的对象,一般用‘this’值,如果这个参数为空,‘undefined’会传递给‘this’值。

注意:

findIndex() 对于空数组,函数是不会执行的,findIndex() 并没有改变数组的原始值。

传入参数:

array.findIndex(function(currentValue, index, arr), thisValue))

currentValue:必须,当前元素。(即原数组中遍历时对应的值)

index:可选,当前元素的索引。(即原数组中遍历时对应的索引值)

arr:可选,当前元素所属的数组对象。(即原数组)

代码:


let arr = [1, 2, 3, 4, 5];
console.log(arr.findIndex((v) => v==4));      // 3

// 实现原理:

let arr = [1, 2, 3, 4, 5];

function findIndex(arr, callback){
    t = false;
    for (const key in arr){
        if (callback(key) === true){
            t = true;
            return key;
        } 
    }
    if (!t) return -1;
}
let find = 4;
let res = findIndex(arr, function(item){
    return arr[item] == find;
});
console.log(res);