Array.prototype.lastIndexOf()
lastIndexOf() 方法用於 Array 例項,它會查詢陣列中給定元素最後出現的位置索引,如果未找到,則返回 -1。該方法從 fromIndex 指定的位置開始向陣列的開頭進行搜尋。
試一試
const animals = ["Dodo", "Tiger", "Penguin", "Dodo"];
console.log(animals.lastIndexOf("Dodo"));
// Expected output: 3
console.log(animals.lastIndexOf("Tiger"));
// Expected output: 1
語法
js
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
引數
searchElement-
要查詢的元素。
fromIndex可選-
搜尋開始位置的基於零的索引,該索引會被 轉換為整數。
- 負數索引表示從陣列末尾開始計數 — 如果
-array.length <= fromIndex < 0,則使用fromIndex + array.length。 - 如果
fromIndex < -array.length,則不會搜尋該陣列,並返回-1。你可以將其想象為從陣列開頭之前一個不存在的位置開始向後搜尋。途中沒有陣列元素,因此永遠找不到searchElement。 - 如果
fromIndex >= array.length或fromIndex被省略或為undefined,則使用array.length - 1,這將導致搜尋整個陣列。你可以將其想象為從陣列末尾之後一個不存在的位置開始向後搜尋。它最終會到達陣列的實際末尾位置,然後開始透過實際的陣列元素向後搜尋。
- 負數索引表示從陣列末尾開始計數 — 如果
返回值
陣列中 searchElement 的最後一個索引;如果未找到,則為 -1。
描述
lastIndexOf() 方法使用 嚴格相等(strict equality)(與 === 運算子演算法相同)來比較 searchElement 與陣列中的元素。NaN 值永遠不會被視為相等,因此當 searchElement 是 NaN 時,lastIndexOf() 始終返回 -1。
lastIndexOf() 方法會跳過 稀疏陣列(sparse arrays) 中的空位。
lastIndexOf() 方法是 通用的(generic)。它只要求 this 值具有 length 屬性和整數鍵屬性。
示例
使用 lastIndexOf()
以下示例使用 lastIndexOf() 在陣列中查詢值。
js
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。
js
const array = [NaN];
array.lastIndexOf(NaN); // -1
查詢元素的所有出現位置
以下示例使用 lastIndexOf 來查詢給定陣列中元素的所有索引,當找到時使用 push() 將它們新增到另一個數組中。
js
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() 來搜尋稀疏陣列中的空位。
js
console.log([1, , 3].lastIndexOf(undefined)); // -1
在非陣列物件上呼叫 lastIndexOf()
lastIndexOf() 方法會讀取 this 的 length 屬性,然後訪問鍵為小於 length 的非負整數的每個屬性。
js
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 2,
3: 5, // ignored by lastIndexOf() since length is 3
};
console.log(Array.prototype.lastIndexOf.call(arrayLike, 2));
// 2
console.log(Array.prototype.lastIndexOf.call(arrayLike, 5));
// -1
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.prototype.lastindexof |
瀏覽器相容性
載入中…