ZetCode

JavaScript findLast 方法

最后修改于 2025 年 4 月 4 日

在本文中,我们将展示如何使用 JavaScript 中的 findLast 方法查找最后一个匹配的元素。

Array findLast 方法

findLast 方法返回数组中满足所提供的测试函数的最后一个元素的值。如果没有任何元素满足测试函数,则返回 undefined

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

该方法以降序方式为每个元素执行回调函数,直到找到回调返回真值的元素。然后它返回该元素并停止搜索。

基本 findLast 示例

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

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

console.log(found);

我们创建了一个数字数组,并使用 findLast 查找最后一个大于 10 的元素。该方法返回 44,这是满足条件的最后一个元素。

$ node main.js
44

查找最后一个偶数

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

main.js
const nums = [1, 3, 4, 7, 8, 9, 12];
const lastEven = nums.findLast((num) => num % 2 === 0);

console.log(lastEven);

我们在数组中搜索最后一个偶数。回调函数检查每个数字是否可被 2 整除。该方法返回 12,这是最后一个偶数。

$ node main.js
12

查找具有属性的最后一个对象

findLast 方法可以与对象数组一起使用。

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

const lastActive = users.findLast((user) => user.active);
console.log(lastActive);

我们在一个用户对象数组中查找最后一个活跃用户。回调检查 active 属性。该方法返回 Bob 的对象,因为它是最后一个活跃用户。

$ node main.js
{ id: 3, name: 'Bob', active: true }

处理未找到匹配项

当没有任何元素满足条件时,findLast 返回 undefined。

main.js
const words = ['apple', 'banana', 'cherry'];
const result = words.findLast((word) => word.startsWith('z'));

console.log(result);  // undefined

我们尝试查找以“z”开头的单词。由于数组中不存在这样的单词,该方法返回 undefined。此行为对于检查是否有任何元素匹配某个条件很有用。

$ node main.js
undefined

使用索引参数

回调函数可以接收当前索引作为其第二个参数。

main.js
const values = [10, 20, 30, 40, 50];
const result = values.findLast((value, index) => {
  console.log(`Checking index ${index}: ${value}`);
  return value > 25;
});

console.log('Result:', result);

我们使用索引参数来记录每次检查。该方法从末尾(索引 4)开始,并在满足条件的索引 2 处停止。这演示了检查的降序顺序。

$ node main.js
Checking index 4: 50
Result: 50

来源

Array findLast - 语言参考

在本文中,我们演示了如何使用 findLast() 方法在 JavaScript 数组中查找最后一个匹配的元素。

作者

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

列出 所有 JS 数组函数。