diff options
| author | Ryan Johnson <rjohnson@mozilla.com> | 2021-04-29 16:16:42 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-04-29 16:16:42 -0700 |
| commit | 95aca4b4d8fa62815d4bd412fff1a364f842814a (patch) | |
| tree | 5e57661720fe9058d5c7db637e764800b50f9060 /files/it/web/javascript/reference/global_objects/array/map/index.html | |
| parent | ee3b1c87e3c8e72ca130943eed260ad642246581 (diff) | |
| download | translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.gz translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.bz2 translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.zip | |
remove retired locales (#699)
Diffstat (limited to 'files/it/web/javascript/reference/global_objects/array/map/index.html')
| -rw-r--r-- | files/it/web/javascript/reference/global_objects/array/map/index.html | 323 |
1 files changed, 0 insertions, 323 deletions
diff --git a/files/it/web/javascript/reference/global_objects/array/map/index.html b/files/it/web/javascript/reference/global_objects/array/map/index.html deleted file mode 100644 index 808b4fc728..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/map/index.html +++ /dev/null @@ -1,323 +0,0 @@ ---- -title: Array.prototype.map() -slug: Web/JavaScript/Reference/Global_Objects/Array/map -tags: - - Array - - ECMAScript 5 - - JavaScript - - Prototype - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/map ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>map()</strong></code> crea un nuovo array con i risultati della chiamata di una funzione fornita su ogni elemento dell'array chiamante.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> - -<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request." </p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>var new_array = arr</var>.map(function <var>callback(currentValue[, index[, array]]) { - </var>// Ritorna un elemento per new_array<var> -}</var>[, <var>thisArg</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione che produce un elemento del nuovo array, prendendo tre argomenti: - <dl> - <dt> </dt> - <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>map</code>.</dd> - </dl> - </dd> - <dt><code>thisArg</code>{{optional_inline}}</dt> - <dd>Valore da utilizzare come <code>this</code> quando viene eseguito <code>callback</code>.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un nuovo array con ciascun elemento che è il risultato della funzione di callback.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>map</code> chiama il <code>callback</code> fornito <strong>una volta per ciascun elemento</strong> in un array, in ordine, e costruisce un nuovo array dai risultati. <code>callback</code> viene invocato solo per gli indici dell'array che hanno valori assegnati, incluso <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a>. Non viene chiamato per gli elementi mancanti dell'array (ovvero, gli indici che non sono mai stati impostati, che sono stati cancellati o a cui non è mai stato assegnato un valore).</p> - -<p>Poichè <code>map</code> costruisce un nuovo array, usarlo quando non si utilizza l'array restituito è un anti-pattern; usa <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach"><code>forEach</code></a> o <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for-of</a></code> invece. Segni che non dovresti usare map: A) Non stai usando l'array restituito, e/o B) Non stai restituendo un valore dal callback.</p> - -<p><code>callback</code> viene invocato con tre argomenti: il valore dell'elemento, l'indice dell'elemento e l'oggetto Array che viene iterato.</p> - -<p>Se viene fornito il parametro <code>thisArg</code> a <code>map</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><code>map</code> non muta l'array su cui è chiamato (sebbene <code>callback</code>, se invocato, possa farlo).</p> - -<p>L'intervallo di elementi elaborati da <code>map</code> viene impostato prima della prima chiamata del <code>callback</code>. Gli elementi aggiunti all'array dopo che la chiamata a <code>map</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>map</code> li visita. Gli elementi che vengono cancellati dopo che la chiamata a <code>map</code> inizia e prima di essere visitati non vengono visitati.</p> - -<p>A causa dell'algoritmo definito nella specifica, se l'array su cui è stata chiamato <code>map</code> è sparso, l'array risultante sarà sparso, mantenendo vuoti gli stessi indici.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Mappare_una_serie_di_numeri_ad_un_array_di_radici_quadrate">Mappare una serie di numeri ad un array di radici quadrate</h3> - -<p>Il seguente codice accetta un array di numeri e crea un nuovo array contenente le radici quadrate dei numeri nel primo array.</p> - -<pre class="brush: js">var numbers = [1, 4, 9]; -var roots = numbers.map(function(num) { -return Math.sqrt(num) -}); -// roots è ora [1, 2, 3] -// numbers è ancora [1, 4, 9] -</pre> - -<h3 id="Usare_map_per_riformattare_gli_oggetti_in_un_array">Usare <code>map</code> per riformattare gli oggetti in un array</h3> - -<p>Il seguente codice accetta un array di oggetti e crea un nuovo array contenente gli oggetti appena riformattati.</p> - -<pre class="brush: js">var kvArray = [{key: 1, value: 10}, - {key: 2, value: 20}, - {key: 3, value: 30}]; - -var reformattedArray = kvArray.map(obj =>{ - var rObj = {}; - rObj[obj.key] = obj.value; - return rObj; -}); -// reformattedArray è ora [{1: 10}, {2: 20}, {3: 30}], - -// kvArray è ancora: -// [{key: 1, value: 10}, -// {key: 2, value: 20}, -// {key: 3, value: 30}] -</pre> - -<h3 id="Mappare_un_array_di_numeri_usando_una_funzione_che_contiene_un_argomento">Mappare un array di numeri usando una funzione che contiene un argomento</h3> - -<p>Il codice seguente mostra come funziona <code>map</code> quando viene utilizzata una funzione che richiede un argomento. L'argomento verrà assegnato automaticamente da ciascun elemento dell'array mentre <code>map</code> itera l'array originale.</p> - -<pre class="brush: js">var numbers = [1, 4, 9]; -var doubles = numbers.map(function(num) { - return num * 2; -}); - -// doubles is now [2, 8, 18] -// numbers is still [1, 4, 9] -</pre> - -<h3 id="Usare_map_genericamente">Usare <code>map</code> genericamente</h3> - -<p>Questo esempio mostra come usare map su una {{jsxref("String")}} per ottenere un array di byte nella codifica ASCII che rappresenta i valori dei caratteri:</p> - -<pre class="brush: js">var a = Array.prototype.map.call('Hello World', function(x) { - return x.charCodeAt(0); -}); -// a ora equivale a [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] -</pre> - -<h3 id="Usare_map_con_querySelectorAll">Usare <code>map</code> con <code>querySelectorAll</code></h3> - -<p>Questo esempio mostra come iterare attraverso una raccolta di oggetti raccolti da <code>querySelectorAll</code>. Questo perchè <code>querySelectorAll</code> restituisce una <em><strong>NodeList</strong></em> che è una raccolta di oggetti.<br> - In questo caso restituiamo sullo schermo tutti i valori delle opzioni selezionate:</p> - -<pre class="brush: js">var elems = document.querySelectorAll('select option:checked'); -var values = Array.prototype.map.call(elems, function(obj) { - return obj.value; -}); -</pre> - -<p>Il modo più semplice sarebbe utilizzare il metodo {{jsxref("Array.from()")}}.</p> - -<h3 id="Caso_d'uso_ingannevole">Caso d'uso ingannevole</h3> - -<p><a href="http://www.wirfs-brock.com/allen/posts/166">(inspired by this blog post)</a></p> - -<p>È normale utilizzare il callback con un argomento (l'elemento che viene attraversato). Alcune funzioni sono anche comunemente utilizzate con un argomento, anche se accettano argomenti opzionali aggiuntivi. Queste abitudini possono portare a comportamenti confusi.</p> - -<pre class="brush: js" dir="rtl">// Consider: -['1', '2', '3'].map(parseInt); -// Mentre ci si potrebbe aspettare [1, 2, 3] -// Il risultato effettivo è [1, NaN, NaN] - -// parseInt è spesso usato con un argomento, ma ne prende due. -// Il primo è un'espressione e il secondo è la radice. -// Alla funzione di callback, Array.prototype.map passa 3 argomenti: -// l'elemento, l'indice e l'array -// Il terzo argomento è ignorato da parseInt, ma non il secondo, -// da qui l'eventuale confusione. Vedi il post del blog per maggiori dettagli -// Se il link non funziona -// ecco un esempio conciso dei passaggi di iterazione: -// parseInt(string, radix) -> map(parseInt(value, index)) -// first iteration (index is 0): parseInt('1', 0) // results in parseInt('1', 0) -> 1 -// second iteration (index is 1): parseInt('2', 1) // results in parseInt('2', 1) -> NaN -// third iteration (index is 2): parseInt('3', 2) // results in parseInt('3', 2) -> NaN - -function returnInt(element) { - return parseInt(element, 10); -} - -['1', '2', '3'].map(returnInt); // [1, 2, 3] -// Il risultato effettivo è un array di numeri (come previsto) - -// Come sopra, ma usando la sintassi della funzione a freccia concisa -['1', '2', '3'].map( str => parseInt(str) ); - -// Un modo più semplice per ottenere quanto sopra, evitando il "gotcha": -['1', '2', '3'].map(Number); // [1, 2, 3] -// ma a differenza di `parseInt` restituirà anche una notazione esponenziale mobile o (risolta): -['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300] -</pre> - -<p>Un output alternativo del metodo map che viene chiamato con parseInt come parametro viene eseguito come segue:</p> - -<pre class="brush: js">var xs = ['10', '10', '10']; - -xs = xs.map(parseInt); - -console.log(xs); -// Il risultato effettivo di 10,NaN,2 potrebbe essere inaspettato in base alla descrizione precedente.</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>map</code> è stato aggiunto allo standard ECMA-262 nella 5a edizione; in quanto tale potrebbe non essere presente in tutte le implementazioni dello standard. Puoi aggirare questo problema inserendo il seguente codice all'inizio degli script, consentendo l'uso di <code>map</code> in implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo {{jsxref("Object")}}, {{jsxref("TypeError")}}, e {{jsxref("Array")}} hanno i loro valori originali e che <code>callback.call</code> restituisce il valore originale di <code>{{jsxref("Function.prototype.call")}}</code>.</p> - -<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.19 -// Reference: http://es5.github.io/#x15.4.4.19 -if (!Array.prototype.map) { - - Array.prototype.map = function(callback/*, thisArg*/) { - - var T, A, 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 A be a new array created as if by the expression new Array(len) - // where Array is the standard built-in constructor with that name and - // len is the value of len. - A = new Array(len); - - // 7. Let k be 0 - k = 0; - - // 8. Repeat, while k < len - while (k < len) { - - var kValue, mappedValue; - - // 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. Let mappedValue be the result of calling the Call internal - // method of callback with T as the this value and argument - // list containing kValue, k, and O. - mappedValue = callback.call(T, kValue, k, O); - - // iii. Call the DefineOwnProperty internal method of A with arguments - // Pk, Property Descriptor - // { Value: mappedValue, - // Writable: true, - // Enumerable: true, - // Configurable: true }, - // and false. - - // In browsers that support Object.defineProperty, use the following: - // Object.defineProperty(A, k, { - // value: mappedValue, - // writable: true, - // enumerable: true, - // configurable: true - // }); - - // For best browser support, use the following: - A[k] = mappedValue; - } - // d. Increase k by 1. - k++; - } - - // 9. return A - return A; - }; -} -</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.19', 'Array.prototype.map')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</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.map")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>L'oggetto {{jsxref("Map")}}</li> - <li>{{jsxref("Array.from()")}}</li> -</ul> |
