JS知识图谱

JavaScript 完全知识体系

Array.prototype.findIndex()

findIndex()方法返回数组中满足提供的测试函数的第一个元素索引。否则返回-1。

语法

arr.findIndex( callbackFunc [, thisArg ])
callbackFunc = function (currentValue, index, array) {
// do something to
}
实例方法参数类型说明
callback用于判定数组成员的回调函数function
thisArg执行回调函数的 this
回调函数参数类型说明
currentValue当前遍历的数组成员any
index当前遍历的数组成员的索引number
array原数组array

示例

代码示例

const arr = [1, 2, 3, 4, 5, 12, 22, 2, 2, 2];
const foo = arr.findIndex(function (currentValue, index, array) {
return currentValue === 2;
});
console.log(foo);
// 1

查找质数

查找数组中首个质数元素的索引。

function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].findIndex(isPrime));
// -1
console.log([4, 6, 7, 12].findIndex(isPrime));
// 2