Array.prototype.findIndex
ES6 新增方法。
const arr = [1, 2, 3, 4, 5];
返回第一个满足条件的数组对应的元素下标
arr.findIndex(item => item > 2); // 2
如果没有找到符合条件的元素,就返回 -1
arr.findIndex(item => item > 5); // -1
数组长度为 0 时,返回 -1
const arr = [];
arr.findIndex(item => item > 2); // -1
稀疏数组是可以正常遍历的,空隙会被填充为 undefined。
findIndex 如果回调返回 true,遍历就停止。
const arr1 = [, 2, , ,];
arr1.findIndex(item => item === 2); // 1
arr1.findIndex(function (item) {
console.log(item);
return item === 2;
// undefined
// 2
}); // 1
findIndex 会遍历空隙,ES5 扩展方法只会遍历有值的索引。
arr1.findIndex(function (item) {
console.log('Gone');
})
参数和 ES5 扩展方法一致
回调函数:遍历的数组元素,元素对应下标,原数组。
回调返回值: bool,遍历在某一次调用回调返回 true 时停止。
第二个参数:更改回调函数内部的 this 指向,默认情况下 this 指向 window,设置第二个参数时,this 指向第二个参数。
在严格模式的默认情况下,this 是 undefined。
arr.findIndex(function (item, index, arr) {
console.log(item, index, arr);
console.log(this);
});
回调函数内部无法改变数组的元素值
arr.findIndex(function (item) {
item += 1;
});
console.log(arr); // [1, 2, 3, 4, 5]
虽然增加了元素,但是遍历只会遍历 2 次,findIndex 和 find 都是在第一次调用回调函数的时候确认数组范围。
arr.findIndex(function (item) {
arr.push(6);
});
删除元素补 undefined,实际上数组元素已被删除
arr.findIndex(function (item) {
if (index === 0) {
arr.splice(1, 1);
}
console.log(item);
});
// 1 3 4 5 undefined
delete 删除元素,不会移动位置,输出 undefined,实际会在原位置补 empty。
arr.findIndex(function (item) {
if (index === 0) {
delete arr[1];
}
console.log(item);
});
// 1 undefined 3 4 5
删除元素下标对应的值,补 undefined,实际数组被删除最后一项
arr.findIndex(function (item) {
if (index === 0) {
arr.pop();
}
console.log(item); // [1, 2, 3, 4]
});
// 1 2 3 4 undefined
代码实现
Array.prototype.$findIndex = function (cb) {
if (this === null) {
throw new TypeError('this is null.');
}
if (typeof cb !== 'function') {
throw new TypeError('callback must be a function');
}
var obj = Object(this),
len = obj.length >> 0,
arg2 = arguments[1],
step = 0;
while (step < len) {
var value = obj[step];
if (cb.apply(arg2, [value, step, obj])) {
return step;
}
step++;
}
return -1;
}
const arr = [1, 2, 3, 4, 5];
arr.$findIndex(function (item, index, arr) {
console.log(item, index, arr);
console.log(this); // window
});
arr.$findIndex(function (item, index, arr) {
return item > 2;
}); // 2
'use strict';
arr.$findIndex(function (item, index, arr) {
console.log(item, index, arr);
console.log(this); // undefined
});