JavaScript Array findIndex()

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

示例

// function that returns odd number
function isOdd(element) {
  return element % 2 !== 0;
}

// defining an array of integers
let numbers = [2, 8, 1, 3, 4];

// returns the index of the first odd number in the array let firstOdd = numbers.findIndex(isOdd);
console.log(firstOdd); // Output: 2

findIndex() 语法

findIndex() 方法的语法是

arr.findIndex(callback(element, index, arr),thisArg)

这里,arr 是一个数组。


findIndex() 参数

findIndex() 方法可以接受两个参数

  • callback - 对数组的每个元素执行的函数。它包含
    • element - 数组的当前元素。
  • thisArg (可选) - 用作 callback 内部 this 的对象。

findIndex() 返回值

  • 返回数组中满足给定函数的第一个元素索引
  • 如果没有任何元素满足函数,则返回-1

示例 1:使用 findIndex() 方法

// function that returns even number
function isEven(element) {
  return element % 2 == 0;
}

// defining an array of integers
let numbers = [1, 45, 8, 98, 7];

// returns the index of the first even number in the array let firstEven = numbers.findIndex(isEven);
console.log(firstEven); // 2

输出

2

在上面的示例中,我们使用 findIndex() 方法查找 numbers 数组中第一个偶数的索引。

isEven() 是一个返回偶数的函数。我们已将 isEven() 作为回调传递给 findIndex() 方法,如下所示:numbers.findIndex(isEven)

该方法返回2,这是 numbers 中第一个偶数 8 的索引。


示例 2:带有箭头函数的 findIndex()

// defining an array
let days = ["Sunday", "Wednesday", "Tuesday", "Friday"];

// returns the first index of 'Wednesday' in the array let index = days.findIndex((day) => day === "Wednesday");
console.log(index); // 1

输出

1

在这里,我们将一个箭头函数作为回调传递给 findIndex() 方法。该方法返回 'Wednesday' 的第一个索引。


示例 3:带有对象元素的 findIndex()

// defining an object 
const team = [
  { name: "Bill", age: 10 },
  { name: "Linus", age: 15 },
  { name: "Alan", age: 20 },
  { name: "Steve", age: 34 },
];

// function that returns age greater than or equal to 18
function isAdult(member) {
  return member.age >= 18;
}

// returns the index of the first element which is // greater than or equal to 18 console.log(team.findIndex(isAdult)); // 2

输出

2

推荐阅读: JavaScript Array find()

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战