aboutsummaryrefslogtreecommitdiff
path: root/files/it/web/javascript/reference/global_objects/array/map/index.html
blob: 808b4fc7286d348bd64889bdff50d58768f07f75 (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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
---
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><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 =&gt;{
   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) -&gt; map(parseInt(value, index))
// first iteration (index is 0): parseInt('1', 0) // results in parseInt('1', 0) -&gt; 1
// second iteration (index is 1): parseInt('2', 1) // results in parseInt('2', 1) -&gt; NaN
// third iteration (index is 2): parseInt('3', 2) // results in parseInt('3', 2) -&gt; 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 =&gt; 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 &gt;&gt;&gt; 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 &gt; 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 &lt; len
    while (k &lt; 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>