aboutsummaryrefslogtreecommitdiff
path: root/files/it/web/javascript/reference/global_objects/array/findindex/index.html
blob: f9f2f65791b6d8baf0083634144ea967eac88905 (plain)
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
170
171
172
173
174
175
176
177
178
179
180
181
182
---
title: Array.prototype.findIndex()
slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex
translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex
---
<div>{{JSRef}}</div>

<p><span class="seoSummary">Il metodo <code><strong>findIndex()</strong></code> restituisce l'<strong>indice</strong> del primo elemento nell'array <strong>che soddisfa la funzione di testing fornita</strong>. Altrimenti, restituisce <code>-1</code>, indicando che nessun elemento ha superato il test.</span></p>

<div>{{EmbedInteractiveExample("pages/js/array-findindex.html","shorter")}}</div>

<div class="hidden">Il sorgente di questo esempio interattivo è salvato una repository GitHub. Se volessi contribuire al progetto degli esempi interattivi, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and inviaci una pull request.</div>

<p>Guarda anche il metodo {{jsxref("Array.find", "find()")}}, che restituisce il <strong>valore</strong> dell'elemento anziché il suo indice.</p>

<h2 id="Sintassi">Sintassi</h2>

<pre class="syntaxbox notranslate"><var>arr</var>.findIndex(<var>callback</var>( <var>elemento</var>[,<em>indice</em>[, <var>array</var>]] )[, <var>thisArg</var>])
</pre>

<h3 id="Parametri">Parametri</h3>

<dl>
 <dt><code><var>callback</var></code></dt>
 <dd>
 <p>Una funzione da eseguire su ognuno dei valori finché la funzione non resitituisce <code>true</code>, indicando che l'elemento che soddisfa la condizione è stato trovato.</p>

 <p>Prende in input tre argomenti:</p>

 <dl>
  <dt><code><var>elemento</var></code></dt>
  <dd>L'elemento dell'array che viene processato.</dd>
  <dt><code><var>indice</var></code> {{optional_inline}}</dt>
  <dd>L'indice dell'elemento dell'array che viene processato.</dd>
  <dt><code><var>array</var></code> {{optional_inline}}</dt>
  <dd>L'array su cui è stato chiamato <code>findIndex()</code>.</dd>
 </dl>
 </dd>
 <dt><code><var>thisArg</var></code> {{optional_inline}}</dt>
 <dd>Oggetto da usare come <code>this</code> quando viene eseguita la <code><var>callback</var></code>.</dd>
</dl>

<h3 id="Valore_restituito">Valore restituito</h3>

<p>L'indice dell primo elemento dell'array che supera il test. Altrimenti <code>-1</code>.</p>

<h2 id="Descrizione">Descrizione</h2>

<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Il metodo </span></font>findIndex()</code> esegue la <code><var>callback</var></code> una volta per ogni indice nell'array finché non trova quello per cui la <code><var>callback</var></code> ritorna un valore {{Glossary("truthy")}}.</p>

<p>Se l'elemento viene trovato, <code>findIndex()</code>  restitutisce immediatamente l'idice dell'elemento. Se <code><var>callback</var></code> non restituisce mai un valore {{Glossary("truthy")}} (o la <code>length</code> dell'array è <code>0</code>), <code>findIndex()</code> restituisce <code>-1</code>.</p>

<div class="blockIndicator note">
<p><strong>Caso limite: </strong>A differenza di altri metodi per array come {{jsxref("Array.some()")}}, <code><var>callback</var></code> viene eseguita anche per gli indici con valori non assegnati.</p>
</div>

<p><code><var>callback</var></code> è invocata con tre argomenti:</p>

<ol>
 <li>Il valore dell'elemento</li>
 <li>L'indice dell'elemento</li>
 <li>L'oggetto Array che viene percorso</li>
</ol>

<p>Se viene passato a <code>findIndex()</code> un parametro <code><var>thisArg</var></code>, sarà usato come <code>this</code> in ogni invocazione di <code><var>callback</var></code>. Se non viene passato si usa {{jsxref("undefined")}}.</p>

<p>The range of elements processed by <code>findIndex()</code> is set before the first invocation of <code><var>callback</var></code>. <code><var>callback</var></code> will not process the elements appended to the array after the call to <code>findIndex()</code> begins. If an existing, unvisited element of the array is changed by <code><var>callback</var></code>, its value passed to the <code><var>callback</var></code> will be the value at the time <code>findIndex()</code> visits the element's index.</p>

<p>Elements that are <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">deleted</a> are still visited.</p>

<h2 id="Polyfill">Polyfill</h2>

<pre class="brush: js notranslate">// https://tc39.github.io/ecma262/#sec-array.prototype.findindex
if (!Array.prototype.findIndex) {
  Object.defineProperty(Array.prototype, 'findIndex', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length &gt;&gt;&gt; 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k &lt; len
      while (k &lt; len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return k.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return k;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return -1.
      return -1;
    },
    configurable: true,
    writable: true
  });
}
</pre>

<p>If you need to support truly obsolete JavaScript engines that do not support {{jsxref("Object.defineProperty")}}, it is best not to polyfill <code>Array.prototype</code> methods at all, as you cannot make them non-enumerable.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Find_the_index_of_a_prime_number_in_an_array">Find the index of a prime number in an array</h3>

<p>The following example returns the index of the first element in the array that is a prime number, or <code>-1</code> if there is no prime number.</p>

<pre class="brush: js notranslate">function isPrime(num) {
  for (let i = 2; num &gt; i; i++) {
    if (num % i == 0) {
      return false;
    }
  }
  return num &gt; 1;
}

console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7)
</pre>

<h3 id="Find_index_using_arrow_function">Find index using arrow function</h3>

<p>The following example finds the index of a fruit using an arrow function:</p>

<pre class="brush: js notranslate">const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];

const index = fruits.findIndex(fruit =&gt; fruit === "blueberries");

console.log(index); // 3
console.log(fruits[index]); // blueberries
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>


<p>{{Compat("javascript.builtins.Array.findIndex")}}</p>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Array.prototype.find()")}}</li>
 <li>{{jsxref("Array.prototype.indexOf()")}}</li>
</ul>