ZetCode

JavaScript findLastIndex 方法

最后修改于 2025 年 4 月 4 日

在本文中,我们展示了如何使用 JavaScript 中的 findLastIndex 方法在数组中查找元素。

数组元素搜索

findLastIndex 方法搜索数组,查找满足提供的测试函数的最后一个元素。它返回找到的元素的索引,如果没有任何元素满足条件,则返回 -1。

当您需要查找与特定条件匹配的元素的最后一次出现的位置时,此方法非常有用。与从头开始搜索的 findIndex 不同,findLastIndex 从末尾开始搜索。

该方法按降序对数组的每个索引执行一次回调函数,直到找到回调返回真值的索引。如果未找到此类元素,则返回 -1。

基本的 findLastIndex 示例

以下示例演示了 findLastIndex 方法的基本用法。

main.js
const numbers = [5, 12, 8, 130, 44, 12];
const isLargeNumber = (element) => element > 10;

const lastIndex = numbers.findLastIndex(isLargeNumber);

console.log(lastIndex);  // Index of last element > 10
console.log(numbers[lastIndex]);  // The element itself

我们创建一个数组并搜索最后一个大于 10 的元素。该方法返回最后一个匹配元素的索引(在本例中为 5)。原始数组保持不变。

$ node main.js
5
12

查找最后一个偶数

此示例展示了如何查找数组中最后一个偶数的索引。

main.js
const nums = [1, 3, 5, 7, 8, 9, 10, 11, 12];
const isEven = (num) => num % 2 === 0;

const lastEvenIndex = nums.findLastIndex(isEven);

console.log(`Last even number at index: ${lastEvenIndex}`);
console.log(`Value: ${nums[lastEvenIndex]}`);

我们定义了一个数字数组和一个用于检查偶数的函数。findLastIndex 方法返回最后一个偶数的索引(在本例中为 8)。回调函数从末尾开始检查每个元素。

$ node main.js
Last even number at index: 8
Value: 12

查找符合条件的最后一个对象

findLastIndex 方法与对象数组配合使用效果很好。

main.js
const users = [
  { id: 1, name: 'John', active: true },
  { id: 2, name: 'Jane', active: false },
  { id: 3, name: 'Bob', active: true },
  { id: 4, name: 'Alice', active: false }
];

const lastActiveIndex = users.findLastIndex(user => user.active);

console.log(`Last active user at index: ${lastActiveIndex}`);
console.log(users[lastActiveIndex]);

我们搜索一个用户对象数组,查找最后一个活动用户。回调检查每个对象的 active 属性。该方法返回 active 为 true 的最后一个对象的索引。

$ node main.js
Last active user at index: 2
{ id: 3, name: 'Bob', active: true }

处理未找到匹配项

当没有任何元素满足条件时,findLastIndex 返回 -1。

main.js
const temperatures = [22, 23, 19, 20, 18];
const isFreezing = (temp) => temp <= 0;

const freezingIndex = temperatures.findLastIndex(isFreezing);

if (freezingIndex === -1) {
  console.log('No freezing temperatures found');
} else {
  console.log(`Last freezing at index: ${freezingIndex}`);
}

我们尝试在数组中找到最后一个冰点温度。由于不存在,该方法返回 -1。此示例演示了正确处理无匹配情况,这对于健壮的代码非常重要。

$ node main.js
No freezing temperatures found

在回调中使用数组元素和索引

回调函数可以访问元素及其索引。

main.js
const words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

const isLongWord = (word, index) => {
  console.log(`Checking index ${index}: ${word}`);
  return word.length > 5;
};

const lastLongWordIndex = words.findLastIndex(isLongWord);

console.log(`Last long word at index: ${lastLongWordIndex}`);

我们搜索最后一个长单词(长度 > 5),同时记录每次检查。回调接收元素及其索引。这演示了该方法如何从数组的末尾处理元素。

$ node main.js
Checking index 4: elderberry
Checking index 3: date
Checking index 2: cherry
Checking index 1: banana
Checking index 0: apple
Last long word at index: 4

来源

数组 findLastIndex - 语言参考

在本文中,我们演示了如何使用 findLastIndex() 方法从末尾搜索 JavaScript 中的数组。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 JS 数组函数。