A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf below:

Array.prototype.lastIndexOf() - JavaScript | MDN

Array.prototype.lastIndexOf()

Baseline Widely available

概述

lastIndexOf() 方法返回数组中给定元素最后一次出现的索引,如果不存在则返回 -1。该方法从 fromIndex 开始向前搜索数组。

尝试一下
const animals = ["Dodo", "Tiger", "Penguin", "Dodo"];

console.log(animals.lastIndexOf("Dodo"));
// Expected output: 3

console.log(animals.lastIndexOf("Tiger"));
// Expected output: 1
语法
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
参数
searchElement

被查找的元素。

fromIndex 可选

以 0 起始的索引,表明反向搜索的起始位置,会被转换为整数。

返回值

数组中该元素最后一次出现的索引,如未找到返回 -1。

描述

lastIndexOf 使用严格相等(与 === 运算符使用的算法相同)比较 searchElement 和数组中的元素。NaN 值永远不会被比较为相等,因此当 searchElement 为 NaN 时 lastIndexOf() 总是返回 -1。

lastIndexOf() 方法会跳过稀疏数组中的空槽。

lastIndexOf() 方法是通用的。它只期望 this 值具有 length 属性和整数键属性。

示例 使用 lastIndexOf()

下例使用 lastIndexOf() 定位数组中的值。

const numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2); // 3
numbers.lastIndexOf(7); // -1
numbers.lastIndexOf(2, 3); // 3
numbers.lastIndexOf(2, 2); // 0
numbers.lastIndexOf(2, -2); // 0
numbers.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));
// 2
console.log(Array.prototype.lastIndexOf.call(arrayLike, 5));
// -1
规范 浏览器兼容性 参见

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4