JavaScript 陣列 lastIndexOf()
示例
查詢“Apple”的最後一個索引
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let index = fruits.lastIndexOf("Apple");
自己動手試一試 »
不止一個 Apple
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple");
自己動手試一試 »
更多示例見下文。
描述
lastIndexOf()
方法返回指定值的最後一個索引(位置)。
如果未找到該值,lastIndexOf()
方法返回 -1。
lastIndexOf()
從指定索引開始,從右到左(從給定位置到陣列開頭)搜尋。
預設情況下,搜尋從最後一個元素開始,到第一個元素結束。
負的起始值從最後一個元素開始計數(但仍然從右到左搜尋)。
陣列查詢方法
方法 | 查詢 |
---|---|
indexOf() | 具有指定值的第一個元素的索引 |
lastIndexOf() | 具有指定值的最後一個元素的索引 |
find() | 透過測試的第一個元素的值 |
findIndex() | 透過測試的第一個元素的索引 |
findLast() | 透過測試的最後一個元素的值 |
findLastIndex() | 透過測試的最後一個元素的索引 |
語法
array.lastIndexOf(item, start)
引數
引數 | 描述 | |
item | 必需。 要搜尋的值。 |
|
start | 可選。 從哪裡開始搜尋。 預設是最後一個元素 (array.length-1)。 負的起始值從最後一個元素開始計數(但仍然從右到左搜尋)。 |
返回值
型別 | 描述 |
一個數字 | 指定專案的位置。 如果未找到專案,則為 -1。 |
更多示例
從位置 4 開始搜尋
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", 4);
自己動手試一試 »
從倒數第二個位置開始搜尋
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", -2);
自己動手試一試 »
瀏覽器支援
lastIndexOf()
是 ECMAScript5 (ES5) 的一個特性。
自 2013 年 7 月以來,所有現代瀏覽器都完全支援 ES5 (JavaScript 2009)
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
2012 年 9 月 | 2012 年 9 月 | 2013 年 4 月 | 2012 年 7 月 | 2013 年 7 月 |