Array.prototype.findLast()
Baseline 2022
Newly available
Since August 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Array
实例的 findLast()
方法以相反的顺序迭代数组,并返回满足提供的测试函数的第一个元素的值。如果没有元素满足测试功能,则返回 undefined
。
¥The findLast()
method of Array
instances iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function.
If no elements satisfy the testing function, undefined
is returned.
如果你需要查找:
¥If you need to find:
- 第一个匹配的元素,使用
find()
。 - 数组中最后一个匹配元素的索引,使用
findLastIndex()
。 - 值的索引,使用
indexOf()
。(它与findIndex()
类似,但检查每个元素是否与值相等,而不是使用测试函数。) - 数组中是否存在某个值,使用
includes()
。同样,它检查每个元素是否与值相等,而不是使用测试函数。 - 如果任何元素满足所提供的测试功能,则使用
some()
。
Try it
语法
参数
返回值
描述
¥Description
findLast()
方法是 迭代法 方法。它按降序索引顺序为数组中的每个元素调用一次提供的 callbackFn
函数,直到 callbackFn
返回 truthy 值。然后 findLast()
返回该元素并停止遍历数组。如果 callbackFn
从未返回真值,则 findLast()
返回 undefined
。请阅读 迭代法 部分,了解有关这些方法一般如何工作的更多信息。
¥The findLast()
method is an iterative method. It calls a provided callbackFn
function once for each element in an array in descending-index order, until callbackFn
returns a truthy value. findLast()
then returns that element and stops iterating through the array. If callbackFn
never returns a truthy value, findLast()
returns undefined
. Read the iterative methods section for more information about how these methods work in general.
callbackFn
会针对数组的每个索引调用,而不仅仅是那些已分配值的索引。稀疏数组 中的空插槽的行为与 undefined
相同。
¥callbackFn
is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined
.
findLast()
方法是 generic。它只期望 this
值具有 length
属性和整数键控属性。
¥The findLast()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
示例
查找数组中与元素属性匹配的最后一个对象
¥Find last object in an array matching on element properties
此示例显示如何根据数组元素的属性创建测试。
¥This example shows how you might create a test based on the properties of array elements.
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "fish", quantity: 1 },
{ name: "cherries", quantity: 5 },
];
// return true inventory stock is low
function isNotEnough(item) {
return item.quantity < 2;
}
console.log(inventory.findLast(isNotEnough));
// { name: "fish", quantity: 1 }
使用箭头函数和解构
¥Using arrow function and destructuring
前面的示例可以使用箭头函数和 对象解构 编写:
¥The previous example might be written using an arrow function and object destructuring:
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "fish", quantity: 1 },
{ name: "cherries", quantity: 5 },
];
const result = inventory.findLast(({ quantity }) => quantity < 2);
console.log(result);
// { name: "fish", quantity: 1 }
查找数组中的最后一个素数
¥Find the last prime number in an array
以下示例返回数组中最后一个素数元素,如果没有素数则返回 undefined
。
¥The following example returns the last element in the array that is a prime number, or undefined
if there is no prime number.
function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
console.log([4, 6, 8, 12].findLast(isPrime)); // undefined, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLast(isPrime)); // 11
使用 callbackFn 的第三个参数
¥Using the third argument of callbackFn
如果你想访问数组中的另一个元素,特别是当你没有引用该数组的现有变量时,array
参数非常有用。以下示例首先使用 filter()
提取正值,然后使用 findLast()
查找小于其邻居的最后一个元素。
¥The array
argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses filter()
to extract the positive values and then uses findLast()
to find the last element that is less than its neighbors.
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const lastTrough = numbers
.filter((num) => num > 0)
.findLast((num, idx, arr) => {
// Without the arr argument, there's no way to easily access the
// intermediate array without saving it to a variable.
if (idx > 0 && num >= arr[idx - 1]) return false;
if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
return true;
});
console.log(lastTrough); // 2
在稀疏数组上使用 findLast()
¥Using findLast() on sparse arrays
访问稀疏数组中的空槽,并按与 undefined
相同的方式处理。
¥Empty slots in sparse arrays are visited, and are treated the same as undefined
.
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];
// Shows all indexes, not just those with assigned values
array.findLast((value, index) => {
console.log(`Visited index ${index} with value ${value}`);
});
// Visited index 6 with value 6
// Visited index 5 with value 5
// Visited index 4 with value undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0
// Shows all indexes, including deleted
array.findLast((value, index) => {
// Delete element 5 on first iteration
if (index === 6) {
console.log(`Deleting array[5] with value ${array[5]}`);
delete array[5];
}
// Element 5 is still visited even though deleted
console.log(`Visited index ${index} with value ${value}`);
});
// Deleting array[5] with value 5
// Visited index 6 with value 6
// Visited index 5 with value undefined
// Visited index 4 with value undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0
对非数组对象调用 findLast()
¥Calling findLast() on non-array objects
findLast()
方法读取 this
的 length
属性,然后访问键为小于 length
的非负整数的每个属性。
¥The findLast()
method reads the length
property of this
and then accesses each property whose key is a nonnegative integer less than length
.
const arrayLike = {
length: 3,
0: 2,
1: 7.3,
2: 4,
3: 3, // ignored by findLast() since length is 3
};
console.log(
Array.prototype.findLast.call(arrayLike, (x) => Number.isInteger(x)),
); // 4
规范
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.findlast |
浏览器兼容性
BCD tables only load in the browser