JavaScript findIndex 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们将展示如何使用 JavaScript 中的 findIndex
方法在数组中查找元素。
数组元素搜索
findIndex
方法返回数组中第一个满足所提供的测试函数的元素的索引。如果没有任何元素满足测试函数,则返回 -1。
当您需要根据特定条件(而不是仅根据其值)来定位元素的位置时,此方法很有用。与 indexOf
不同,findIndex
可以处理复杂的搜索条件。
该方法会为数组中的每个索引执行一次回调函数,直到找到回调返回真值的索引。原始数组在操作后保持不变。
findIndex 基本示例
以下示例演示了 findIndex
方法的基本用法。
main.js
const numbers = [5, 12, 8, 130, 44]; const isLargeNumber = (element) => element > 13; const firstLargeIndex = numbers.findIndex(isLargeNumber); console.log(firstLargeIndex); console.log(numbers); // Original array remains unchanged
我们在数组中搜索第一个大于 13 的数字。回调函数测试每个元素,直到找到匹配项。该方法返回第一个匹配元素的索引。
$ node main.js 3 [ 5, 12, 8, 130, 44 ]
在数组中查找对象
findIndex
方法特别适用于搜索对象数组。
main.js
const users = [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' } ]; const index = users.findIndex(user => user.name === 'Jane'); console.log(index);
我们在数组中搜索名称为“Jane”的用户对象。回调函数检查每个对象的 name 属性。该方法返回第一个匹配对象的索引。
$ node main.js 1
处理未找到匹配项
当没有元素满足条件时,findIndex
返回 -1。
main.js
const fruits = ['apple', 'banana', 'orange']; const index = fruits.findIndex(fruit => fruit === 'grape'); if (index === -1) { console.log('Fruit not found'); } else { console.log(`Found at index ${index}`); }
我们尝试在水果数组中查找“grape”。由于它不存在,该方法返回 -1。此行为对于检查元素是否存在很有用。
$ node main.js Fruit not found
使用 thisArg 参数
findIndex
方法接受一个可选的 thisArg
参数,用于在回调中设置 this
值。
main.js
const inventory = [ { name: 'apples', quantity: 2 }, { name: 'bananas', quantity: 0 }, { name: 'cherries', quantity: 5 } ]; function isStockLow(item) { return item.quantity < this.threshold; } const index = inventory.findIndex(isStockLow, { threshold: 3 }); console.log(index);
我们使用 thisArg
将一个阈值传递给我们的回调函数。该方法找到第一个数量低于阈值的项目。这种方法使回调更灵活。
$ node main.js 0
使用复杂条件查找索引
findIndex
方法可以处理复杂的搜索条件。
main.js
const data = [ { id: 1, value: 10, active: true }, { id: 2, value: 20, active: false }, { id: 3, value: 30, active: true }, { id: 4, value: 40, active: true } ]; const index = data.findIndex(item => { return item.active && item.value > 25; }); console.log(index);
我们搜索第一个值大于 25 的活动项目。回调结合了多个条件。该方法返回满足所有条件的第一个项目的索引。
$ node main.js 2
来源
在本文中,我们演示了如何使用 findIndex
方法在 JavaScript 数组中定位元素。
作者
列出 所有 JS 数组函数。