diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
commit | da78a9e329e272dedb2400b79a3bdeebff387d47 (patch) | |
tree | e6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/it/web/javascript/reference/global_objects/array/foreach | |
parent | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff) | |
download | translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2 translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip |
initial commit
Diffstat (limited to 'files/it/web/javascript/reference/global_objects/array/foreach')
-rw-r--r-- | files/it/web/javascript/reference/global_objects/array/foreach/index.html | 331 |
1 files changed, 331 insertions, 0 deletions
diff --git a/files/it/web/javascript/reference/global_objects/array/foreach/index.html b/files/it/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..dbd4919852 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,331 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Prototype + - Referenza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p>Il metodo <code><strong>forEach()</strong></code> esegue una funzione fornita una volta per ogni elemento dell'array.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + + + +<h2 id="Sintassi">Sintassi</h2> + +<pre class="syntaxbox"><var>arr</var>.forEach(<var>callback(currentValue [, index [, array]])</var>[, <var>thisArg</var>]);</pre> + +<h3 id="Parametri">Parametri</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Funzione da eseguire per ciascun elemento, prendendo tre argomenti:</dd> + <dd> + <dl> + <dt><code>currentValue</code></dt> + <dd>L'elemento corrente in elaborazione nell'array.</dd> + <dt><code>index</code> {{optional_inline}}</dt> + <dd>L'indice dell'elemento corrente in elaborazione nell'array.</dd> + <dt><code>array</code> {{optional_inline}}</dt> + <dd>L'array a cui viene applicato <code>forEach()</code>.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{optional_inline}}</dt> + <dd>Valore da utilizzare come <code>this</code> quando si esegue <code>callback</code>.</dd> +</dl> + +<h2 id="Descrizione">Descrizione</h2> + +<p><code>forEach()</code> esegue il <code>callback</code> fornito una volta per ciascun elemento presente nell'array in ordine crescente. Non è invocato per le proprietà dell'indice che sono state eliminate o non inizializzate (ad esempio su array sparsi).</p> + +<p><code>callback</code> viene invocato con tre argomenti:</p> + +<ul> + <li>il valore dell'elemento</li> + <li>l'indice dell'elemento</li> + <li>l'array che deve essere iterato</li> +</ul> + +<p>Se viene fornito il parametro <code>thisArg</code> a <code>forEach()</code>, verrà utilizzato come valore <code>this</code> del callback. Altrimenti, il valore {{jsxref("undefined")}} sarà usato come valore <code>this</code>. Il valore <code>this</code> alla fine osservabile da <code>callback</code> è determinato secondo <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">le consuete regole per determinare il <code>this</code> visto da una funzione</a>.</p> + +<p>L'intervallo di elementi elaborati da <code>forEach()</code> viene impostato prima della prima chiamata del <code>callback</code>. Gli elementi aggiunti all'array dopo che la chiamata <code>forEach()</code> inizia non saranno calcolati da <code>callback</code>. Se i valori degli elementi esistenti dell'array vengono modificati, il valore passato a <code>callback</code> sarà il valore al momento in cui <code>forEach()</code> li visita; gli elementi che vengono cancellati prima di essere visitati non vengono visitati. Se gli elementi già visitati vengono rimossi (ad esempio usando {{jsxref("Array.prototype.shift()", "shift()")}}) durante l'iterazione, gli elementi successivi verranno saltati - vedi l'esempio sotto.</p> + +<p><code>forEach()</code> esegue la funzione <code>callback</code> una volta per ogni elemento dell'array; a differenza di {{jsxref("Array.prototype.map()", "map()")}} o {{jsxref("Array.prototype.reduce()", "reduce()")}} restituisce sempre {{jsxref("undefined")}} e non è concatenabile. Il tipico caso d'uso è eseguire effetti collaterali alla fine del chain.</p> + +<p><code>forEach()</code> non muta l'array su cui è chiamato (sebbene <code>callback</code>, se invocato, possa farlo).</p> + +<div class="note"> +<p>Non c'è modo di fermare o interrompere un loop <code>forEach()</code> se non lanciando un'eccezione. Se hai bisogno di un simile comportamento, il metodo <code>forEach()</code> è lo strumento sbagliato.</p> + +<p>La risoluzione anticipata può essere eseguita con:</p> + +<ul> + <li>Un loop semplice</li> + <li>Un loop <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> + +<p>Gli altri metodi per array: {{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.find()")}}, e {{jsxref("Array.prototype.findIndex()")}} testano gli elementi dell'array con un predicato restituendo un valore di verità per determinare se è necessaria un'ulteriore iterazione.</p> +</div> + +<h2 id="Esempi">Esempi</h2> + +<h3 id="Convertire_un_loop_for_in_forEach">Convertire un loop for in forEach</h3> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +// prima +for (let i=0; i<items.length; i++) { + copy.push(items[i]); +} + +// dopo +items.forEach(function(item) { + copy.push(item); +}); +</pre> + +<h3 id="Stampa_del_contenuto_di_un_array">Stampa del contenuto di un array</h3> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> Per visualizzare il contenuto di un array nella console, puoi utilizzare <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/table">console.table()</a></code> che stamperà una versione formattata dell'array. L'esempio seguente illustra un altro modo per farlo, usando <code>forEach()</code>.</p> +</div> + +<p>Il seguente codice logga una linea per ogni elemento in un array:</p> + +<pre class="brush:js">function logArrayElements(element, index, array) { + console.log('a[' + index + '] = ' + element); +} + +// Nota che l'indice 2 viene saltato poiché non vi è alcun elemento +// in quella posizione nell'array. +[2, 5, , 9].forEach(logArrayElements); +// logga: +// a[0] = 2 +// a[1] = 5 +// a[3] = 9 +</pre> + +<h3 id="Usare_thisArg">Usare <code>thisArg</code></h3> + +<p>Il seguente esempio (inventato) aggiorna le proprietà di un oggetto da ciascuna voce dell'array:</p> + +<pre class="brush:js">function Counter() { + this.sum = 0; + this.count = 0; +} +Counter.prototype.add = function(array) { + array.forEach(function(entry) { + this.sum += entry; + ++this.count; + }, this); + // ^---- Nota +}; + +const obj = new Counter(); +obj.add([2, 5, 9]); +obj.count; +// 3 +obj.sum; +// 16 +</pre> + +<p>Poiché il parametro <code>thisArg</code> (<code>this</code>) viene fornito a <code>forEach()</code>, viene passato a <code>callback</code> ogni volta che viene richiamato, per essere utilizzato come valore <code>this</code>.</p> + +<div class="note"> +<p>Se si passa l'argomento della funzione utilizzando <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">un'espressione della funzione a freccia</a> il parametro <code>thisArg</code> può essere omesso poiché le funzioni a freccia associano in modo lessicale il valore {{jsxref("Operators/this", "this")}}.</p> +</div> + +<h3 id="Una_funzione_di_copia_di_oggetti">Una funzione di copia di oggetti</h3> + +<p>Il seguente codice crea una copia di un dato oggetto. Esistono diversi modi per creare una copia di un oggetto; il seguente è solo un modo e viene presentato per spiegare come funziona <code>Array.prototype.forEach()</code> usando le funzioni di meta proprietà ECMAScript 5 <code>Object.*</code>.</p> + +<pre class="brush: js">function copy(obj) { + const copy = Object.create(Object.getPrototypeOf(obj)); + const propNames = Object.getOwnPropertyNames(obj); + + propNames.forEach(function(name) { + const desc = Object.getOwnPropertyDescriptor(obj, name); + Object.defineProperty(copy, name, desc); + }); + + return copy; +} + +const obj1 = { a: 1, b: 2 }; +const obj2 = copy(obj1); // obj2 looks like obj1 now +</pre> + +<h3 id="Se_l'array_viene_modificato_durante_l'iterazione_altri_elementi_potrebbero_essere_saltati.">Se l'array viene modificato durante l'iterazione, altri elementi potrebbero essere saltati.</h3> + +<p>L'esempio seguente registra "uno", "due", "quattro". Quando viene raggiunta la voce contenente il valore "due", la prima voce dell'intero array viene spostata, il che comporta il trasferimento di tutte le voci rimanenti in una posizione. Poiché l'elemento "quattro" è ora in una posizione precedente nell'array, "tre" verrà saltato. <code>forEach()</code> non esegue una copia dell'array prima di iterare.</p> + +<pre class="brush:js">var words = ['uno', 'due', 'tre', 'quattro']; +words.forEach(function(word) { + console.log(word); + if (word === 'due') { + words.shift(); + } +}); +// uno +// due +// quattro +</pre> + +<h3 id="Appiattire_un_array">Appiattire un array</h3> + +<p>Il seguente esempio è qui solo per scopi didattici. Se si desidera appiattire un array usando metodi built-in, è possibile utilizzare {{jsxref("Array.prototype.flat()")}} (che dovrebbe essere parte di ES2019 e già implementato in alcuni browser).</p> + +<pre class="brush: js">/** + * Flattens ha passato un array in un array dimensionale + * + * @params {array} arr + * @returns {array} + */ +function flatten(arr) { + const result = [] + + arr.forEach((i) => { + if (Array.isArray(i)) { + result.push(...flatten(i)) + } else { + result.push(i) + } + }) + + return result +} + +// Uso +const problem = [1, 2, 3, [4, 5, [6, 7], 8, 9]] + +flatten(problem) // [1, 2, 3, 4, 5, 6, 7, 8, 9] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>forEach()</code> è stato aggiunto allo standard ECMA-262 nella quinta edizione; in quanto tale potrebbe non essere presente in altre implementazioni dello standard. È possibile aggirare questo problema inserendo il seguente codice all'inizio degli script, consentendo l'uso di <code>forEach()</code> nelle implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo {{jsxref("Object")}} e {{jsxref("TypeError")}} hanno i loro valori originali e quel <code>callback.call()</code> valuta il valore originale di {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function(callback/*, thisArg*/) { + + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling toObject() passing the + // |this| value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get() internal + // method of O with the argument "length". + // 3. Let len be toUint32(lenValue). + var len = O.length >>> 0; + + // 4. If isCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let + // T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat while k < len. + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator. + // b. Let kPresent be the result of calling the HasProperty + // internal method of O with argument Pk. + // This step can be combined with c. + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Call the Call internal method of callback with T as + // the this value and argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return undefined. + }; +} +</pre> + +<h2 id="Specifiche">Specifiche</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specifica</th> + <th scope="col">Stato</th> + <th scope="col">Commento</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definizione iniziale Implementato in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="Vedi_anche">Vedi anche</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.filter()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> |