在 JavaScript 中,Array.findLast() 方法用于以相反的顺序迭代数组元素,并返回满足所提供函数的第一个元素的值。如果没有元素满足提供的函数中的条件,则返回 “undefined” 作为结果。
此方法不对空数组元素执行函数。除此之外,此方法不会修改原始数组。
findLast() 方法自 2022 年 8 月以来是新可用的方法。此方法适用于最新的设备和浏览器。它可能不适用于较旧的设备或浏览器。
语法
以下是 JavaScript Array.findLast() 方法的语法 -
findLast(callbackFn, thisArg)
参数
此方法接受两个参数。下面描述相同 -
- callbackFn − 要为数组中的每个元素执行的函数。它需要三个参数 -
- element − 数组中正在处理的当前元素。
- index (可选) − 数组中正在处理的当前元素的索引。
- array (可选)− 调用数组 every() 。
- thisArg(可选)- 要作为其 this 值传递给函数的值。
返回值
此 方法返回通过提供的 testing 函数的最后一个元素的值;否则为 'undefined'。
示例 1
在以下示例中,我们使用 JavaScript Array.findLastIndex() 方法查找数组中的最后一个偶数 -
<html>
<body>
<script>
const numbers = [1, 2, 3, 4, 5];
const lastValue = numbers.findLast((num) => num % 2 === 0);
document.write(lastValue);
</script>
</body>
</html>
输出
它返回 '4' 作为结果,因为它是数组中的最后一个偶数。
4
示例 2
在下面的示例中,我们将查找数组中以特定字母 ('a') 开头的最后一个字符串元素 -
<html>
<body>
<script>
const words = ['apple', 'banana', 'avocado', 'orange', 'grape'];
const lastValue = words.findLast((word) => word.startsWith('a'));
document.write(lastValue);
</script>
</body>
</html>
输出
它返回 “avocado” 作为结果,因为它是满足条件的最后一个单词。
avocado
示例 3
在这里,我们找到数组中值大于 10 的最后一个元素 -
<html>
<body>
<script>
const numbers = [5, 8, 12, 15, 20, 4];
const lastValue = numbers.findLast((num) => num > 10);
document.write(lastValue);
</script>
</body>
</html>
输出
20
示例 4
在下面的示例中,我们找到数组中的最后一个元素,它是一个偶数 -
<html>
<body>
<script>
const numbers = [1, 3, 5, 7, 9];
const lastValue = numbers.findLast((num) => num % 2 === 0);
document.write(lastValue);
</script>
</body>
</html>
输出
它返回 'undefined' 作为结果,因为数组中没有元素满足函数。
undefined