JavaScript配列lastIndexOf()
例
「Apple」の最後のインデックスを検索します。
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let index = fruits.lastIndexOf("Apple");
複数のリンゴ:
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple");
以下のその他の例。
定義と使用法
このlastIndexOf()
メソッドは、指定された値の最後のインデックス(位置)を返します。
lastIndexOf()
値が見つからない場合、メソッドは-1を返します。
はlastIndexOf()
指定されたインデックスから始まり、右から左に検索します。
defaltを使用すると、検索は最後の要素で開始し、最初の要素で終了します。
負の開始値は最後の要素からカウントされます(ただし、右から左に検索します)。
関連項目:
構文
array.lastIndexOf(item, start)
パラメーター
Parameter | Description | |
item | Required. The value to search for. |
|
start | Optional. Where to start the search. Default is the last element (array.length-1). Negative start values counts from the last element (but still searches from right to left). |
戻り値
タイプ | 説明 |
数 | 指定されたアイテムの位置。 -アイテムが見つからない場合は-1。 |
ブラウザのサポート
lastIndexOf()
ECMAScript5(ES5)機能です。
ES5(JavaScript 2009)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
その他の例
位置4から検索を開始します。
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", 4);
最後から2番目の位置から検索を開始します。
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", -2);