此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Array.prototype.lastIndexOf()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
lastIndexOf() 方法返回数组中给定元素最后一次出现的索引,如果不存在则返回 -1。该方法从fromIndex 开始向前搜索数组。
In this article
尝试一下
const animals = ["Dodo", "Tiger", "Penguin", "Dodo"];console.log(animals.lastIndexOf("Dodo"));// Expected output: 3console.log(animals.lastIndexOf("Tiger"));// Expected output: 1语法
lastIndexOf(searchElement)lastIndexOf(searchElement, fromIndex)参数
searchElement被查找的元素。
fromIndex可选以 0 起始的索引,表明反向搜索的起始位置,会被转换为整数。
- 如果
fromIndex < 0,则从数组末尾开始倒数计数——即使用fromIndex + array.length的值。 - 如果
fromIndex < -array.length,则不搜索数组并返回-1。从概念上讲,你可以把它想象成从数组开始之前不存在的位置开始反向搜索,这条路径上没有任何数组元素,因此searchElement永远不会被找到。 - 如果
fromIndex >= array.length或者省略了fromIndex,则使用array.length - 1,这会导致搜索整个数组。可以将其理解为从数组尾部之后不存在的位置开始向前搜索。最终会访问到数组最后一个元素,并继续向前开始实际搜索数组元素。
- 如果
返回值
数组中该元素最后一次出现的索引,如未找到返回-1。
描述
lastIndexOf 使用严格相等(与=== 运算符使用的算法相同)比较searchElement 和数组中的元素。NaN 值永远不会被比较为相等,因此当searchElement 为NaN 时lastIndexOf() 总是返回-1。
lastIndexOf() 方法会跳过稀疏数组中的空槽。
lastIndexOf() 方法是通用的。它只期望this 值具有length 属性和整数键属性。
示例
>使用 lastIndexOf()
下例使用lastIndexOf() 定位数组中的值。
const numbers = [2, 5, 9, 2];numbers.lastIndexOf(2); // 3numbers.lastIndexOf(7); // -1numbers.lastIndexOf(2, 3); // 3numbers.lastIndexOf(2, 2); // 0numbers.lastIndexOf(2, -2); // 0numbers.lastIndexOf(2, -1); // 3你不能用lastIndexOf() 来搜索NaN。
const array = [NaN];array.lastIndexOf(NaN); // -1查找元素出现的所有索引
下例使用lastIndexOf 查找到一个元素在数组中所有的索引(下标),并在找到它们时用push 将它们添加到另一个数组中。
const indices = [];const array = ["a", "b", "a", "c", "a", "d"];const element = "a";let idx = array.lastIndexOf(element);while (idx !== -1) { indices.push(idx); idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;}console.log(indices);// [4, 2, 0]需要注意的是,这里必须单独处理idx === 0 的情况,因为如果该元素是数组的第一个元素,则无论fromIndex 参数的值为何,它总是会被找到。这与indexOf 方法不同。
在稀疏数组上使用 lastIndexOf()
你不能使用lastIndexOf() 来搜索稀疏数组中的空槽。
console.log([1, , 3].lastIndexOf(undefined)); // -1在非数组对象上调用 lastIndexOf()
lastIndexOf() 方法读取this 的length 属性,然后访问每个整数索引。
const arrayLike = { length: 3, 0: 2, 1: 3, 2: 2,};console.log(Array.prototype.lastIndexOf.call(arrayLike, 2));// 2console.log(Array.prototype.lastIndexOf.call(arrayLike, 5));// -1规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.lastindexof> |