1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
|
---
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
---
<div>{{JSRef}}</div>
<p>Il metodo <code><strong>lastIndexOf()</strong></code> 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 <code>fromIndex</code>.</p>
<div>{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}</div>
<p class="hidden">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 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviaci una pull request.</p>
<h2 id="Sintassi">Sintassi</h2>
<pre class="syntaxbox"><var>arr</var>.lastIndexOf(<var>searchElement</var>)
<var>arr</var>.lastIndexOf(<var>searchElement</var>, <var>fromIndex</var>)
</pre>
<h3 id="Parametri">Parametri</h3>
<dl>
<dt><code>searchElement</code></dt>
<dd>Elemento da trovare nell' array.</dd>
<dt><code>fromIndex</code> {{optional_inline}}</dt>
<dd>L'indice da cui iniziare a cercare al contrario. Di defaults la lunghezza dell' array meno uno (<code>arr.length - 1</code>), 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.</dd>
</dl>
<h3 id="Valori_restituiti">Valori restituiti</h3>
<p>L'ultimo indice dell' elemento nell' array; <strong>-1</strong> se non trovato.</p>
<h2 id="Descrizione">Descrizione</h2>
<p><code>lastIndexOf</code> compara <code>searchElement</code> a gli elementi dell' array usando <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">strict equality</a> (lo stesso metodo usato ===, o triple-equals, operator).</p>
<h2 id="Esempi">Esempi</h2>
<h3 id="Utilizzo_di_lastIndexOf">Utilizzo di <code>lastIndexOf</code></h3>
<p>L'esempio seguente usa <code>lastIndexOf</code> per trovare i valori in un array.</p>
<pre class="brush: js">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
</pre>
<h3 id="Trovare_tutte_le_posizioni_di_un_elemento">Trovare tutte le posizioni di un elemento</h3>
<p>Il seguente esempio usa <code>lastIndexOf</code> per trovare tutti gli elementi nell' array, usando {{jsxref("Array.prototype.push", "push")}} per essere aggiunti in un array come vengono trovati.</p>
<pre class="brush: js">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]
</pre>
<p>Nota che non abbiamo considerato <code>idx == 0</code>perchè l'elemento sarà sempre troavto indipendemente da <code>il parametro fromIndex</code> se è il primo elemento dell'array. TQuesto è diveso dal metodo {{jsxref("Array.prototype.indexOf", "indexOf")}}.</p>
<h2 id="Polyfill">Polyfill</h2>
<p><code>lastIndexOf</code> è 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 <code>lastIndexOf</code> 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.</p>
<pre class="brush: js">// 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;
};
}
</pre>
<p>Ancora, nota che questa implementazione mira alla compatibilità assoluta con <code>lastIndexOf</code> in Firefox e SpiderMonkey JavaScript engine, includendo alcuni casi che sono considerati estremi. ISe hai intenzione di usare questo in applicazioni reali, potresti calcolare <code>from</code> con un codice meno complicato se ignori questi casi.</p>
<h2 id="Descrizione_2">Descrizione</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Descrizione</th>
<th scope="col">Stato</th>
<th scope="col">Commento</th>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td>Definizione iniziale. Implementato in JavaScript 1.6.</td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td>
<td>{{Spec2('ES6')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="Compatibilità_con_il_browser">Compatibilità con il browser</h2>
<div>
<div class="hidden">La tabella della compatibilità in questa pagina è stata generata da strutture dati. Se vorresti contribuire ai dati, perfavore da un' occhiata a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una pull request.</div>
<p>{{Compat("javascript.builtins.Array.lastIndexOf")}}</p>
</div>
<h2 id="Note_di_compatibilità">Note di compatibilità</h2>
<ul>
<li>Partendo da Firefox 47 {{geckoRelease(47)}}, <code>questo metodo non restituirà più -0</code>. Per esempio, <code>[0].lastIndexOf(0, -0)</code> Ora restituirà sempre <code>+0</code> ({{bug(1242043)}}).</li>
</ul>
<h2 id="Guarda_anche">Guarda anche</h2>
<ul>
<li>{{jsxref("Array.prototype.indexOf()")}}</li>
<li>{{jsxref("TypedArray.prototype.lastIndexOf()")}}</li>
</ul>
|