A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex below:

Array.prototype.findIndex() - JavaScript | MDN

Array.prototype.findIndex()

Baseline Widely available

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

另请参阅 find() 方法,它返回满足测试函数的第一个元素(而不是它的索引)。

尝试一下
const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3
语法
findIndex(callbackFn)
findIndex(callbackFn, thisArg)
参数
callbackFn

为数组中的每个元素执行的函数。它应该返回一个真值以指示已找到匹配元素,否则返回一个假值。该函数被调用时将传入以下参数:

element

数组中当前正在处理的元素。

index

正在处理的元素在数组中的索引。

array

调用了 findIndex() 的数组本身。

thisArg 可选

执行 callbackFn 时用作 this 的值。参见迭代方法。

返回值

数组中第一个满足测试条件的元素的索引。否则返回 -1。

描述

findIndex() 是一种迭代方法。它按照索引升序依次遍历数组中的每个元素,并调用提供的 callbackFn 函数,直到 callbackFn 返回一个真值。然后 findIndex() 返回该元素的索引并停止遍历数组。如果 callbackFn 从未返回一个真值,则 findIndex() 返回 -1。

callbackFn 被调用来处理数组的每一个索引,而不仅仅是那些有值的索引。在稀疏数组中,未赋值的空槽与 undefined 表现相同。

findIndex() 不会改变被调用的数组,但是提供给 callbackFn 的函数可能会改变它。但需要注意的是,在第一次调用 callbackFn 之前,数组的长度会被保存。因此:

警告: 上述类型的并发修改经常导致难以理解的代码,通常应避免(特殊情况除外)。

findIndex() 方法是通用的。它只期望 this 值具有 length 属性和整数键属性。

示例 寻找数组中的首个素数的索引

以下示例返回数组中第一个素数的索引,如果没有素数则返回 -1。

function isPrime(n) {
  if (n < 2) {
    return false;
  }
  if (n % 2 === 0) {
    return n === 2;
  }
  for (let factor = 3; factor * factor <= n; factor += 2) {
    if (n % factor === 0) {
      return false;
    }
  }
  return true;
}

console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1,没有找到
console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2(array[2] 是 7)

备注: isPrime() 实现仅供演示。在实际应用中,为了避免重复计算,会使用大量记忆化的算法,例如埃拉托斯特尼筛法。

在稀疏数组上使用 findIndex()

你可以搜索稀疏数组中的 undefined 并来获取空槽的索引。

console.log([1, , 3].findIndex((x) => x === undefined)); // 1
在非数组对象上调用 findIndex()

findIndex() 方法读取 this 的 length 属性,并访问每个整数索引。

const arrayLike = {
  length: 3,
  0: 2,
  1: 7.3,
  2: 4,
};
console.log(
  Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)),
); // 1
规范 浏览器兼容性 参见

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4