--- title: Array.prototype.lastIndexOf() slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf tags: - Array - ECMAScript 5 - JavaScript - Protototipo - Prototype - metodo - polyfill translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf ---
Il metodo lastIndexOf()
ritorna l'ultimo indice nel quale l'elemento dato può essere trovato nell' array, o -1 se non presente. L'array verrà controllato al contrario, partendo da fromIndex
.
Il codice sorgere per questo esempio interattivo è conservato all' interno di una repository di GitHub. Se vuoi contribuire all progetto di esempi interattivi, perfavore clona https://github.com/mdn/interactive-examples e inviaci una pull request.
arr.lastIndexOf(searchElement) arr.lastIndexOf(searchElement, fromIndex)
searchElement
fromIndex
{{optional_inline}}arr.length - 1
), quindi cercherà in tutto l'array. Se l'indice è uguale o maggiore alla lunghezza dell' array, l' elemento sarà cercato in tutto l'array. Se negativo, Verrà preso come offset dalla fine dell' array. Nota che anche se l'indice è negativo, l'array sarà controllato comunque al contrario. ISe l'indice calcolato è minore di 0, verrà ritornato -1, quindi non verrà effettuata la ricerca.L'ultimo indice dell' elemento nell' array; -1 se non trovato.
lastIndexOf
compara searchElement
a gli elementi dell' array usando strict equality (lo stesso metodo usato ===, o triple-equals, operator).
lastIndexOf
L'esempio seguente usa lastIndexOf
per trovare i valori in un array.
var 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
Il seguente esempio usa lastIndexOf
per trovare tutti gli elementi nell' array, usando {{jsxref("Array.prototype.push", "push")}} per essere aggiunti in un array come vengono trovati.
var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var 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]
Nota che non abbiamo considerato idx == 0
perchè l'elemento sarà sempre troavto indipendemente da il parametro fromIndex
se è il primo elemento dell'array. TQuesto è diveso dal metodo {{jsxref("Array.prototype.indexOf", "indexOf")}}.
lastIndexOf
è stato aggiunto nello standard ECMA-262 nella 5° edizione; come può non essere trovato in altre implementazioni nello standard. Puoi aggirare questa cosa inserendo il seguente codice all' inizio del tuo script, permettendoti di usare lastIndexOf
anche se non supportato nativamente.Questo algorittmo è esattamente quello descritto da ECMA-262, 5° edizione, assumendo{{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Number")}}, {{jsxref("Math.floor")}}, {{jsxref("Math.abs")}}, e {{jsxref("Math.min")}} abbiano il loro valore originale.
// Production steps of ECMA-262, Edition 5, 15.4.4.15 // Reference: http://es5.github.io/#x15.4.4.15 if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var n, k, t = Object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = len - 1; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { n = 0; } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; }
Ancora, nota che questa implementazione mira alla compatibilità assoluta con lastIndexOf
in Firefox e SpiderMonkey JavaScript engine, includendo alcuni casi che sono considerati estremi. ISe hai intenzione di usare questo in applicazioni reali, potresti calcolare from
con un codice meno complicato se ignori questi casi.
Descrizione | Stato | Commento |
---|---|---|
{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}} | {{Spec2('ES5.1')}} | Definizione iniziale. Implementato in JavaScript 1.6. |
{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.Array.lastIndexOf")}}
questo metodo non restituirà più -0
. Per esempio, [0].lastIndexOf(0, -0)
Ora restituirà sempre +0
({{bug(1242043)}}).