From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../global_objects/array/concat/index.html | 188 ------- .../global_objects/array/copywithin/index.html | 180 ------- .../global_objects/array/entries/index.html | 77 --- .../global_objects/array/every/index.html | 184 ------- .../reference/global_objects/array/fill/index.html | 155 ------ .../global_objects/array/filter/index.html | 245 --------- .../reference/global_objects/array/find/index.html | 216 -------- .../global_objects/array/findindex/index.html | 182 ------- .../reference/global_objects/array/flat/index.html | 159 ------ .../global_objects/array/flatmap/index.html | 142 ----- .../global_objects/array/foreach/index.html | 331 ------------ .../reference/global_objects/array/from/index.html | 242 --------- .../global_objects/array/includes/index.html | 162 ------ .../reference/global_objects/array/index.html | 480 ----------------- .../global_objects/array/indexof/index.html | 226 -------- .../global_objects/array/isarray/index.html | 133 ----- .../reference/global_objects/array/join/index.html | 112 ---- .../reference/global_objects/array/keys/index.html | 74 --- .../global_objects/array/lastindexof/index.html | 169 ------ .../global_objects/array/length/index.html | 129 ----- .../reference/global_objects/array/map/index.html | 323 ------------ .../reference/global_objects/array/of/index.html | 92 ---- .../reference/global_objects/array/pop/index.html | 117 ----- .../reference/global_objects/array/push/index.html | 142 ----- .../global_objects/array/reduce/index.html | 576 --------------------- .../global_objects/array/reverse/index.html | 133 ----- .../global_objects/array/slice/index.html | 241 --------- .../reference/global_objects/array/some/index.html | 202 -------- .../reference/global_objects/array/sort/index.html | 267 ---------- .../global_objects/array/splice/index.html | 163 ------ .../global_objects/array/tostring/index.html | 80 --- .../global_objects/array/unshift/index.html | 98 ---- .../global_objects/array/values/index.html | 87 ---- 33 files changed, 6307 deletions(-) delete mode 100644 files/it/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/copywithin/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/entries/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/every/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/fill/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/filter/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/find/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/findindex/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/flat/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/flatmap/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/foreach/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/from/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/includes/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/indexof/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/isarray/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/keys/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/lastindexof/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/length/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/map/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/push/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/reduce/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/some/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/sort/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/splice/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/tostring/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/unshift/index.html delete mode 100644 files/it/web/javascript/reference/global_objects/array/values/index.html (limited to 'files/it/web/javascript/reference/global_objects/array') diff --git a/files/it/web/javascript/reference/global_objects/array/concat/index.html b/files/it/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index 9d8d7d6629..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -tags: - - Array - - aggiungi elementi array - - concat -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef}}
- -

Il metodo concat() ritorna un nuovo array costituito dall'array sul quale è stato invocato (joined array) e dagli array e/o valori passati come argomenti.

- -

Sintassi

- -
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
- -

Parametri

- -
-
valueN
-
Array e/o valori da concatenare nel nuovo array. Vedere la descrizione sotto per i dettagli.
-
- -

Valore restituito

- -

Una nuova istanza di {{jsxref("Array")}}.

- -

Descrizione

- -

Il metodo concat crea un nuovo array costituito dagli elementi dell'oggetto su cui è stato invocato, seguiti in ordine da ciascun argomento o dagli elementi di ciascun argomento, se quest'ultimo è esso stesso un array.

- -

Il metodo concat non altera l'oggetto this (l'array originale) o gli elementi passati come parametri, ma ritorna una copia degli stessi che contiene copie degli elementi costituenti gli argomenti. Gli elementi degli array originali sono copiati in quello nuovo secondo le seguenti regole:

- - - -
var a = [1, 2]
-var b = {c:1}
-var d = a.concat(b)
-
-// d[2] is {c: 1}
-b.c=10
-// d[2] is now {c: 10}
-
- - - -
-

Note: Concatenando i valori di diversi array o valori, si lasciano gli originali inalterati. Inoltre, qualsiasi operazione sui nuovi array (eccetto le operazioni su elementi che siano riferimenti a oggetti) non avrà effetto alcuno sugli originali e viceversa.

-
- -

Esempi

- -

Concatenare due array

- -

Il codice seguente concatena due array:

- -
var alpha = ['a', 'b', 'c'];
-var numeric = [1, 2, 3];
-
-alpha.concat(numeric);
-// Risultato: ['a', 'b', 'c', 1, 2, 3]
-
- -

Concatenare tre array

- -

Il codice seguente concatena tre array:

- -
var num1 = [1, 2, 3],
-    num2 = [4, 5, 6],
-    num3 = [7, 8, 9];
-
-var nums = num1.concat(num2, num3);
-
-
-console.log(nums);
-// Risultato: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
- -

Concatenare valori ad un array

- -

Il codice seguente concatena dei valori a quelli presenti in un array:

- -
var alpha = ['a', 'b', 'c'];
-
-var alphaNumeric = alpha.concat(1, [2, 3]);
-
-console.log(alphaNumeric);
-// Risultato: ['a', 'b', 'c', 1, 2, 3]
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificheStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale, implementato in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Compatibilità con i Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
BrowserChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto Base{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
BrowserAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto Base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Vedere anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/copywithin/index.html b/files/it/web/javascript/reference/global_objects/array/copywithin/index.html deleted file mode 100644 index 65e00abe47..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/copywithin/index.html +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: Array.prototype.copyWithin() -slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin -translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin ---- -
{{JSRef}}
- -

Il metodo copyWithin() copia superficialmente una parte di un array in un'altra locazione dello stesso array e lo restituisce, senza modificare la sua dimensione.

- -
{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}
- - - -

Sintassi

- -
arr.copyWithin(target)
-arr.copyWithin(target, start)
-arr.copyWithin(target, start, end)
-
- -

Parametri

- -
-
target
-
Indice zero-based fino al quale copiare la sequenza. Se negativo, target sarà impostato all'ultimo elemento dell'array.
-
Se target è pari o più grande di arr.length, non sarà copiato nulla. Se target è posizionato dopo start, la sequenza copiata, sarà ritagliata per poter rientrare in arr.length.
-
start {{optional_inline}}
-
Indice zero-based dal quale si comincia a copiare gli elementi. Se negativo, start comincerà a contare dalla fine.
-
Se start è omesso, copyWithin copierà dall'inizio (default 0).
-
end {{optional_inline}}
-
Indice zero-based che indica l'ultimo indice dal quale copiare. copyWithin copia fino ad end ma non lo include. Se negativo, end sarà contato dalla fine.
-
Se end è omesso, copyWithin copierà fino alla fine (default arr.length).
-
- -

Valore di ritorno

- -

L'array modificato.

- -

Descrizione

- -

copyWithin ha le stesse funzionalità di memmove provenienti da C e C++, ed è un metodo molto performante per spostare i dati di un {{jsxref("Array")}}. Questa modifica si applica specialmente a {{jsxref("TypedArray/copyWithin", "TypedArray")}} metodo con lo stesso nome. La sequenza è copiata e incollata come una singola operzione; la sequenza incollata avrà i valori copiati anche se essi si sovrappongono.

- -

La funzione copyWithin è intenzionalmente generic, e non richiede che i suoi argomenti siano {{jsxref("Array")}} object.

- -

copyWithin è un metodo mutabile. Non altera la lunghezza di this, ma cambia il suo contenuto e crea nuove proprietà se necessario..

- -

Esempi

- -
[1, 2, 3, 4, 5].copyWithin(-2);
-// [1, 2, 3, 1, 2]
-
-[1, 2, 3, 4, 5].copyWithin(0, 3);
-// [4, 5, 3, 4, 5]
-
-[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
-// [4, 2, 3, 4, 5]
-
-[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
-// [1, 2, 3, 3, 4]
-
-[].copyWithin.call({length: 5, 3: 1}, 0, 3);
-// {0: 1, 3: 1, length: 5}
-
-// ES2015 Typed Arrays are subclasses of Array
-var i32a = new Int32Array([1, 2, 3, 4, 5]);
-
-i32a.copyWithin(0, 2);
-// Int32Array [3, 4, 5, 4, 5]
-
-// On platforms that are not yet ES2015 compliant:
-[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
-// Int32Array [4, 2, 3, 4, 5]
-
- -

Polyfill

- -
if (!Array.prototype.copyWithin) {
-  Array.prototype.copyWithin = function(target, start/*, end*/) {
-    // Steps 1-2.
-    if (this == null) {
-      throw new TypeError('this is null or not defined');
-    }
-
-    var O = Object(this);
-
-    // Steps 3-5.
-    var len = O.length >>> 0;
-
-    // Steps 6-8.
-    var relativeTarget = target >> 0;
-
-    var to = relativeTarget < 0 ?
-      Math.max(len + relativeTarget, 0) :
-      Math.min(relativeTarget, len);
-
-    // Steps 9-11.
-    var relativeStart = start >> 0;
-
-    var from = relativeStart < 0 ?
-      Math.max(len + relativeStart, 0) :
-      Math.min(relativeStart, len);
-
-    // Steps 12-14.
-    var end = arguments[2];
-    var relativeEnd = end === undefined ? len : end >> 0;
-
-    var final = relativeEnd < 0 ?
-      Math.max(len + relativeEnd, 0) :
-      Math.min(relativeEnd, len);
-
-    // Step 15.
-    var count = Math.min(final - from, len - to);
-
-    // Steps 16-17.
-    var direction = 1;
-
-    if (from < to && to < (from + count)) {
-      direction = -1;
-      from += count - 1;
-      to += count - 1;
-    }
-
-    // Step 18.
-    while (count > 0) {
-      if (from in O) {
-        O[to] = O[from];
-      } else {
-        delete O[to];
-      }
-
-      from += direction;
-      to += direction;
-      count--;
-    }
-
-    // Step 19.
-    return O;
-  };
-}
- -

Specificazioni

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ES2016', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES2016')}} 
{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ESDraft')}} 
- -

Compatibilità browser

- -
- - -

{{Compat("javascript.builtins.Array.copyWithin")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/entries/index.html b/files/it/web/javascript/reference/global_objects/array/entries/index.html deleted file mode 100644 index 31e156afb8..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/entries/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Array.prototype.entries() -slug: Web/JavaScript/Reference/Global_Objects/Array/entries -translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries ---- -
{{JSRef}}
- -

Il metodo entries() restituisce un nuovo oggetto Array Iterator contenente delle coppie chiave/valore per ogni indice presente nell'array.

- -
{{EmbedInteractiveExample("pages/js/array-entries.html")}}
- - - -

Sintassi

- -
a.entries()
- -

Valore ritornato

- -

Un nuovo oggetto iterator {{jsxref("Array")}}.

- -

Esempi

- -

Utilizzo nel for…of

- -
var a = ['a', 'b', 'c'];
-var iterator = a.entries();
-
-for (let e of iterator) {
-  console.log(e);
-}
-// [0, 'a']
-// [1, 'b']
-// [2, 'c']
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ESDraft')}} 
- -

Compatibilità con il browser

- -
- - -

{{Compat("javascript.builtins.Array.entries")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/every/index.html b/files/it/web/javascript/reference/global_objects/array/every/index.html deleted file mode 100644 index c1f3238ad6..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/every/index.html +++ /dev/null @@ -1,184 +0,0 @@ ---- -title: Array.prototype.every() -slug: Web/JavaScript/Reference/Global_Objects/Array/every -translation_of: Web/JavaScript/Reference/Global_Objects/Array/every ---- -
{{JSRef}}
- -

Il metodo every() controlla che tutti gli elementi all'interno dell'array passino il test implementato dalla funzione fornita.

- -
{{EmbedInteractiveExample("pages/js/array-every.html")}}
- - - -

Sintassi

- -
arr.every(callback[, thisArg])
- -

Parametri

- -
-
callback
-
Funzione da testare per ciascun elemento, che prende tre argomenti: -
-
currentValue (required)
-
L'elemento corrente che viene elaborato all'interno dell'array.
-
index{{Optional_inline}}
-
L'indice dell'elemento corrente che viene elaborato all'interno dell'array.
-
array{{Optional_inline}}
-
L'array every chiamato.
-
-
-
thisArg{{Optional_inline}}
-
Opzionale. Valore da utilizzare come this durante l'esecuzione della callback.
-
- -

Valore di ritorno

- -

true se la funzione callback ritorna un valore {{Glossary("truthy")}} per ciascun elemento dell'array; altrimenti, false.

- -

Descrizione

- -

Il metodo every  esegue la funzione callback fornita una volta per ciascun elemento presente all'interno dell'array finché non ne trova uno per il quale la callback ritorna un valore {{Glossary("falsy")}}. Altrimenti, se la callback ritorna un valore {{Glossary("truthy")}} per tutti gli elementi, every ritorna truecallback viene invocata solo per gli indici dell'array che hanno un valore assegnato; non viene invocata per gli indici che sono stati eliminati o ai quali non è mai stato assegnato un valore.

- -

callback viene invocata con tre argomenti: il valore dell'elemento, l'indice dell'elemento, e l'Array oggetto che viene attraversato. 

- -

Se il parametro thisArg viene fornito a every, esso verrà usato come valore this per la callback. Altrimenti, il valore undefined verrà usato al suo posto come valore this.  Il valore this, ultimo osservabile dalla callback, viene determinato secondo le usuali regole per determinare il this visto da una funzione.

- -

every non modifica l'array in cui viene chiamato.

- -

Il range di elementi processati da every viene impostato prima della prima invocazione di callback. Gli elementi che vengono appesi all'inizio dell'array dopo la chiamata a every  non verranno visitati dalla callback. Se gli elementi esistenti dell'array vengono cambiati, il loro valore passato a callback sarà il valore al momento in cui every li visiterà; gli elementi cancellati non sono visitati.

- -

every agisce come il quantificatore "for all" in matematica. In particolare, per un array vuoto, esso ritorna true. (E' vacuously true che tutti gli elementi dell' empty set soddisfano qualsiasi condizione data.)

- -

Esempi

- -

Controllo sulla grandezza di tutti gli elementi dell'array

- -

Il seguente esempio controlla che tutti gli elementi dell'array siano maggiori di 10.

- -
function isBigEnough(element, index, array) {
-  return element >= 10;
-}
-[12, 5, 8, 130, 44].every(isBigEnough);   // false
-[12, 54, 18, 130, 44].every(isBigEnough); // true
-
- -

Utilizzando arrow functions

- -

Arrow functions forniscono una sintassi più breve per lo stesso test.

- -
[12, 5, 8, 130, 44].every(x => x >= 10); // false
-[12, 54, 18, 130, 44].every(x => x >= 10); // true
- -

Polyfill

- -

every è stato aggiunto allo standard ECMA-262 nella 5a edizione; per questo motivo potrebbe non essere presente in altre implementazioni dello standard. Potrai aggirare il problema inserendo il seguente codice all'inizio dei tuoi scripts, permettendo così l'utilizzo di every in implementazioni che non lo supportano nativamente. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo che Object e TypeError abbiano i loro valori originali e che callbackfn.call valuti sul valore originale di {{jsxref("Function.prototype.call")}}.

- -
if (!Array.prototype.every) {
-  Array.prototype.every = function(callbackfn, thisArg) {
-    'use strict';
-    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(callbackfn) is false, throw a TypeError exception.
-    if (typeof callbackfn !== 'function') {
-      throw new TypeError();
-    }
-
-    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
-    if (arguments.length > 1) {
-      T = thisArg;
-    }
-
-    // 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. Let testResult be the result of calling the Call internal method
-        //     of callbackfn with T as the this value and argument list
-        //     containing kValue, k, and O.
-        var testResult = callbackfn.call(T, kValue, k, O);
-
-        // iii. If ToBoolean(testResult) is false, return false.
-        if (!testResult) {
-          return false;
-        }
-      }
-      k++;
-    }
-    return true;
-  };
-}
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementata in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}} 
- -

Compatibilità browser

- -
- - -

{{Compat("javascript.builtins.Array.every")}}

-
- -

Vedere anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/fill/index.html b/files/it/web/javascript/reference/global_objects/array/fill/index.html deleted file mode 100644 index 043696f554..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/fill/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Array.prototype.fill() -slug: Web/JavaScript/Reference/Global_Objects/Array/fill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill ---- -
{{JSRef}}
- -

Il metodo fill() assegna un valore statico a tutti gli elementi di un array compresi tra un indice iniziale ed un indice finale.

- -
var numbers = [1, 2, 3]
-numbers.fill(1);
-
-// results in [1, 1, 1]
- -

Sintassi

- -
arr.fill(value)
-arr.fill(value, start)
-arr.fill(value, start, end)
-
- -

Parametri

- -
-
value
-
Valore statico da assegnare agli elementi dell'array.
-
start {{optional_inline}}
-
Indice iniziale, default uguale a 0.
-
end {{optional_inline}}
-
Indice finale, default uguale a this.length.
-
- -

Valore di ritorno

- -

L'array modificato.

- -

Descrizione

- -

L'intervallo di elementi da assegnare è compreso tra [start, end).

- -

Il metodo  fill accetta fino a tre argomenti: value, start and end. Gli argomenti start e end  sono opzionali con valori di default rispettivamente di 0 di length dell'oggetto this .

- -

Se start è negativo, viene interpretato come length+start dove length è la lunghezza dell'array. Se end è negativo, viene intrpretato come length+end.

- -

La funzione fill è volutamente generica, non richiede che il suo valore this sia un Array.

- -

Il metodo fill è mutabile, ovvero modifica l'oggetto this  e  lo restituisce modificato, ovvero non ne restituisce una copia modificata.

- -

Quando al metodo fill viene passato un oggetto, il metodo effettuerà una copia dell'oggetto e  assegnerà agli elementi dell'Array un riferimento alla copia.

- -

Examples

- -
[1, 2, 3].fill(4);               // [4, 4, 4]
-[1, 2, 3].fill(4, 1);            // [1, 4, 4]
-[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
-[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
-[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
-[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
-[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
-[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
-[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
-Array(3).fill(4);                // [4, 4, 4]
-[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}
-
-// Objects by reference.
-var arr = Array(3).fill({}) // [{}, {}, {}];
-arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
-
- -

Polyfill

- -
if (!Array.prototype.fill) {
-  Object.defineProperty(Array.prototype, 'fill', {
-    value: function(value) {
-
-      // Steps 1-2.
-      if (this == null) {
-        throw new TypeError('this is null or not defined');
-      }
-
-      var O = Object(this);
-
-      // Steps 3-5.
-      var len = O.length >>> 0;
-
-      // Steps 6-7.
-      var start = arguments[1];
-      var relativeStart = start >> 0;
-
-      // Step 8.
-      var k = relativeStart < 0 ?
-        Math.max(len + relativeStart, 0) :
-        Math.min(relativeStart, len);
-
-      // Steps 9-10.
-      var end = arguments[2];
-      var relativeEnd = end === undefined ?
-        len : end >> 0;
-
-      // Step 11.
-      var final = relativeEnd < 0 ?
-        Math.max(len + relativeEnd, 0) :
-        Math.min(relativeEnd, len);
-
-      // Step 12.
-      while (k < final) {
-        O[k] = value;
-        k++;
-      }
-
-      // Step 13.
-      return O;
-    }
-  });
-}
-
- -

Se hai necessità di supportare engine Javascript veramente obsolete che non supportano Object.defineProperty, è meglio non usare affatto il polyfill per il medoto Array.prototype perchè non è possibile renderlo non enumerabile.

- -

Specifiche

- - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.fill")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/filter/index.html b/files/it/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 33d24d38b6..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -
{{JSRef}}
- -

Il metodo filter() crea un nuovo array contentente tutti gli elementi che passano il test implementato dalla funzione. 

- -
function isBigEnough(value) {
-  return value >= 10;
-}
-
-var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
-// filtered is [12, 130, 44]
-
- -

Sintassi

- -
var new_array = arr.filter(callback[, thisArg])
- -

Parametri

- -
-
callback
-
Funzione predicato per testare ciascun elemento dell'array. Restituisce true se l'elemento va mantenuto, false altrimenti. Essa prende in input tre argomenti:
-
-
-
element
-
L'elemento corrente nell'array processato.
-
index
-
L' indice dell'elemento corrente processato nell'array.
-
array
-
l'array su cui filter è stato chiamato.
-
-
-
thisArg
-
Opzionale. Valore da usare come this quando si esegue callback.
-
- -

Valore restituito

- -

Un nuovo array con gli elementi che hanno passato il test.

- -

Descrizione

- -

filter() chiama funzione ricorsiva (callback) fornita una volta per ciascun elemento dell'array e crea un nuovo array con tutti quei valori in cui la callback ha restituito un valore true.. callback viene invocata solo per gli indici dell'array a cui sono associati dei valori; non viene invocata per inidici in cui sono stati cancellati i valori o in cui non sono stati definiti valori. Gli elementi dell'array che non superano il test vengono semplicemente ignorati, non venendo così inseriti nel nuovo array.

- -

callback viene invocata con tre argomenti:

- -
    -
  1. il valore dell'elemento
  2. -
  3. l'indice dell'elemento
  4. -
  5. l' Array oggetto da passare
  6. -
- -

Se viene fornito a filter un parametro thisArg , questo verrà passato a sua volta a callback quando verrà invocata per usarlo come valore di this . Altrimenti verrà passato un valore undefined per essere usato come valore di this. Il valore  this osservabile in definitiva dalla funzione callback viene scelto seguendo le usuali regole di determinazione dei this visti da una funzione.

- -

filter() non muta l'array sul quale viene chiamata.

- -

La gamma di element processati da filter() viene impostata prima della invocazione della callback. Gli elementi che vengono mesi nell'array da filtrare dopo l'invocazione di filter() non verranno esaminati dalla callback. Se ci sono elementi dell'array da fitrare i cui valori vengono cambiati o vengono cancellati dopo la applicazione di filter() ,  questi nel tempo di chamata di filter() verranno testati dalla  callback nello stato previo alla loro modifica. Elementi cancellati prima della applicazione di  filter()  non vengono visitati.

- -

Esempi

- -

Filtrare tutti i piccoli valori

- -

Il seguente esempio usa filter() per realizzare un array filtrato che non contenga elementi di valore inferiore a 10.

- -
function isBigEnough(value) {
-  return value >= 10;
-}
-
-var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
-// filtered is [12, 130, 44]
-
- -

Filtrare entrate non valide in JSON

- -

Il sequente esempio di utilizzo di filter() crea un json filtrato di elementi con valido  id numerico.

- -
var arr = [
-  { id: 15 },
-  { id: -1 },
-  { id: 0 },
-  { id: 3 },
-  { id: 12.2 },
-  { },
-  { id: null },
-  { id: NaN },
-  { id: 'undefined' }
-];
-
-var invalidEntries = 0;
-
-function isNumber(obj) {
-  return obj!== undefined && typeof(obj) === 'number' && !isNaN(obj);
-}
-
-function filterByID(item) {
-  if (isNumber(item.id)) {
-    return true;
-  }
-  invalidEntries++;
-  return false;
-}
-
-var arrByID = arr.filter(filterByID);
-
-console.log('Filtered Array\n', arrByID);
-// Array filtrato
-// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
-
-console.log('Quantità di entrate non valide = ', invalidEntries);
-// Quantità di entrate non valide = 4
-
- -

Polyfill

- -

filter() è stato aggiunto allo standard ECMA-262 nella quinta edizione; potrebbe essere non presente in tutte le implementazioni dello standard. Puoi sempre inserire il seguente codice nei tuoi script per poter usare filter() nelle implementazioni ECMA-262 che non lo supportanto nativamente. Questo algoritmo è esattamente quello nella specifica ECMA-262, quinta edizione, assumendo che  fn.call valuti il valore originale di  {{jsxref("Function.prototype.call()")}},e che {{jsxref("Array.prototype.push()")}} abbia il suo valore originale.

- -
if (!Array.prototype.filter) {
-  Array.prototype.filter = function(fun/*, thisArg*/) {
-    'use strict';
-
-    if (this === void 0 || this === null) {
-      throw new TypeError();
-    }
-
-    var t = Object(this);
-    var len = t.length >>> 0;
-    if (typeof fun !== 'function') {
-      throw new TypeError();
-    }
-
-    var res = [];
-    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
-    for (var i = 0; i < len; i++) {
-      if (i in t) {
-        var val = t[i];
-
-        // NOTE: Technically this should Object.defineProperty at
-        //       the next index, as push can be affected by
-        //       properties on Object.prototype and Array.prototype.
-        //       But that method's new, and collisions should be
-        //       rare, so use the more-compatible alternative.
-        if (fun.call(thisArg, val, i, t)) {
-          res.push(val);
-        }
-      }
-    }
-
-    return res;
-  };
-}
-
- -

Specificazioni

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}} -

Definizione iniziale. Implementato in javascript 1.6.

-
{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}}
- -

Compatibilità Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/find/index.html b/files/it/web/javascript/reference/global_objects/array/find/index.html deleted file mode 100644 index c215ff79e7..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/find/index.html +++ /dev/null @@ -1,216 +0,0 @@ ---- -title: Array.prototype.find() -slug: Web/JavaScript/Reference/Global_Objects/Array/find -tags: - - Array - - ECMAScript 2015 - - ECMAScript6 - - JavaScript - - Prototype - - Riferimento - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/find ---- -
{{JSRef}}
- -

Il metodo find() restituisce il valore del primo elemento nell'array che soddisfi la funzione di test passata come argomento. Altrimenti viene restituito {{jsxref("undefined")}}.

- -
function isBigEnough(element) {
-  return element >= 15;
-}
-
-[12, 5, 8, 130, 44].find(isBigEnough); // 130
- -

Vedi anche il metodo {{jsxref("Array.findIndex", "findIndex()")}}, che restituisce l'indice dell'elemento trovato nell'array invece del suo valore.

- -

Se hai bisogno di trovare la posizione di un elemento o determinare se un elemento esiste o meno nell'array, puoi usare i metodi {{jsxref("Array.prototype.indexOf()")}} o {{jsxref("Array.prototype.includes()")}}.

- -

Sintassi

- -
arr.find(callback[, thisArg])
- -

Parametri

- -
-
callback
-
Funzione da eseguire per ogni valore contenuto nell'array, richiede tre argomenti: -
-
element
-
L'elemento nell'array che dev'essere testato.
-
index
-
L'indice dell'elemento nell'array che dev'essere testato.
-
array
-
L'array sul quale è stato chiamato il find.
-
-
-
thisArg
-
Opzionale. L'oggetto da utilizzare come this durante l'esecuzione della callback.
-
- -

Valore restituito

- -

Un valore dell'array se un elemento soddisfa la condizione; altrimenti, {{jsxref("undefined")}}.

- -

Descrizione

- -

Il metodo find esegue la funzione di callback una sola volta per ciascun elemento nell'array finché non ne trova uno per il quale la funzione di callback restituisca true. Se tale elemento viene trovato, find restituisce immediatamente il valore di quell'elemento. Altrimenti, find restituisce {{jsxref("undefined")}}. La funzione callback è invocata solo per quegli indici dell'array per i quali esiste un valore; non viene invocata per quegli indici che sono stati cancellati o ai quali non è mai stato assegnato alcun valore.

- -

Alla funzione callback vengono passati tre parametri: il valore dell'elemento, l'indice dell'elemento e l'oggetto Array che si sta esplorando.

- -

Se viene passato il parametro thisArg al metodo find, questo verrà usato come this per ciascuna invocazione della funzione callback. Altrimenti viene utilizzato {{jsxref("undefined")}}.

- -

Il metodo find non modifica l'array sul quale viene chiamato.

- -

L'intervallo di elementi analizzati dal metodo find è impostato prima della prima invocazione della callback. Gli elementi aggiunti all'array successivamente alla chiamata del metodo find non verranno analizzate dalla callback. Se un elemento dell'array esistente, ma non ancora visitato, viene modificato dalla callback, il valore passato alla funzione callback sarà il valore contenuto nel momento in cui il metodo find visita l'indice di quell'elemento; gli elementi eliminati non vengono visitati.

- -

Esempi

- -

Trova un oggetto in un array tramite una sua proprietà

- -
var inventario = [
-    {name: 'mele', quantity: 2},
-    {name: 'banane', quantity: 0},
-    {name: 'ciliegie', quantity: 5}
-];
-
-function findCherries(fruit) {
-    return fruit.name === 'ciliegie';
-}
-
-console.log(inventario.find(findCherries));
-// { name: 'ciliegie', quantity: 5 }
- -

Trova un numero primo in un array

- -

L'esempio seguente trova un elemento nell'array che sia un numero primo (o restituisce {{jsxref("undefined")}} se non ce ne sono).

- -
function isPrime(element, index, array) {
-  var start = 2;
-  while (start <= Math.sqrt(element)) {
-    if (element % start++ < 1) {
-      return false;
-    }
-  }
-  return element > 1;
-}
-
-console.log([4, 6, 8, 12].find(isPrime)); // undefined, non trovato
-console.log([4, 5, 8, 12].find(isPrime)); // 5
-
- -

Polyfill

- -

Questo metodo è stato aggiunto nella specifica ECMAScript 2015 e potrebbe non ancora essere disponibile in tutte le implementazioni JavaScript. Comunque, puoi aggiungere il metodo Array.prototype.find() utilizzando il seguente snippet:

- -
if (!Array.prototype.find) {
-  Object.defineProperty(Array.prototype, 'find', {
-    value: function(predicate) {
-     'use strict';
-     if (this == null) {
-       throw new TypeError('Array.prototype.find called on null or undefined');
-     }
-     if (typeof predicate !== 'function') {
-       throw new TypeError('predicate must be a function');
-     }
-     var list = Object(this);
-     var length = list.length >>> 0;
-     var thisArg = arguments[1];
-
-     for (var i = 0; i !== length; i++) {
-       if (predicate.call(thisArg, this[i], i, list)) {
-         return this[i];
-       }
-     }
-     return undefined;
-    }
-  });
-}
-
- -

Se hai la necessità di supportare motori JavaScript molto obsoleti che non supportano Object.defineProperty, sarebbe meglio non aggiungere per niente il metodo  Array.prototype.find(), poiché potresti renderli non-enumerabili.

- -

Specifiche

- - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
- -

Compatibilità browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome(45.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}12{{CompatOpera(32.0)}}{{CompatSafari("7.1")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileEdgeOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}12{{CompatNo}}8.0
-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/findindex/index.html b/files/it/web/javascript/reference/global_objects/array/findindex/index.html deleted file mode 100644 index f9f2f65791..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/findindex/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Array.prototype.findIndex() -slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex -translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex ---- -
{{JSRef}}
- -

Il metodo findIndex() restituisce l'indice del primo elemento nell'array che soddisfa la funzione di testing fornita. Altrimenti, restituisce -1, indicando che nessun elemento ha superato il test.

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

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

- -

Sintassi

- -
arr.findIndex(callback( elemento[,indice[, array]] )[, thisArg])
-
- -

Parametri

- -
-
callback
-
-

Una funzione da eseguire su ognuno dei valori finché la funzione non resitituisce true, indicando che l'elemento che soddisfa la condizione è stato trovato.

- -

Prende in input tre argomenti:

- -
-
elemento
-
L'elemento dell'array che viene processato.
-
indice {{optional_inline}}
-
L'indice dell'elemento dell'array che viene processato.
-
array {{optional_inline}}
-
L'array su cui è stato chiamato findIndex().
-
-
-
thisArg {{optional_inline}}
-
Oggetto da usare come this quando viene eseguita la callback.
-
- -

Valore restituito

- -

L'indice dell primo elemento dell'array che supera il test. Altrimenti -1.

- -

Descrizione

- -

Il metodo findIndex() esegue la callback una volta per ogni indice nell'array finché non trova quello per cui la callback ritorna un valore {{Glossary("truthy")}}.

- -

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

- -
-

Caso limite: A differenza di altri metodi per array come {{jsxref("Array.some()")}}, callback viene eseguita anche per gli indici con valori non assegnati.

-
- -

callback è invocata con tre argomenti:

- -
    -
  1. Il valore dell'elemento
  2. -
  3. L'indice dell'elemento
  4. -
  5. L'oggetto Array che viene percorso
  6. -
- -

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

- -

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

- -

Elements that are deleted are still visited.

- -

Polyfill

- -
// 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 >>> 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 < len
-      while (k < 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
-  });
-}
-
- -

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

- -

Examples

- -

Find the index of a prime number in an array

- -

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

- -
function isPrime(num) {
-  for (let i = 2; num > i; i++) {
-    if (num % i == 0) {
-      return false;
-    }
-  }
-  return num > 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)
-
- -

Find index using arrow function

- -

The following example finds the index of a fruit using an arrow function:

- -
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
-
-const index = fruits.findIndex(fruit => fruit === "blueberries");
-
-console.log(index); // 3
-console.log(fruits[index]); // blueberries
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.findIndex")}}

-
- -

See also

- - diff --git a/files/it/web/javascript/reference/global_objects/array/flat/index.html b/files/it/web/javascript/reference/global_objects/array/flat/index.html deleted file mode 100644 index 3c5a81ed4b..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/flat/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Array.prototype.flat() -slug: Web/JavaScript/Reference/Global_Objects/Array/flat -tags: - - Array - - JavaScript - - Prototype - - Referenza - - flat - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat ---- -
- -
{{JSRef}}
- -

Il metodo flat() crea un nuovo array con tutti gli elementi dei propri sotto-array concatenati ricorsivamente al suo interno fino alla profondità specificata.

- - - - - -

Sintassi

- -
var newArray = arr.flat([profondità]);
- -

Parametri

- -
-
profondità {{optional_inline}}
-
Il livello di profondità che specifica quanto a fondo la struttura di array annidati deve essere appianata. Default a 1.
-
- -

Valore di ritorno

- -

Un nuovo array con gli elementi dei sotto-array concatenati al suo interno.

- -

Esempi

- -

Appianare array annidati

- -
var arr1 = [1, 2, [3, 4]];
-arr1.flat();
-// [1, 2, 3, 4]
-
-var arr2 = [1, 2, [3, 4, [5, 6]]];
-arr2.flat();
-// [1, 2, 3, 4, [5, 6]]
-
-var arr3 = [1, 2, [3, 4, [5, 6]]];
-arr3.flat(2);
-// [1, 2, 3, 4, 5, 6]
-
- -

Appianamento e slot vuoti negli array

- -

Il metodo flat rimuove gli slot vuoti in un array:

- -
var arr4 = [1, 2, , 4, 5];
-arr4.flat();
-// [1, 2, 4, 5]
-
- -

Alternative

- -

reduce e concat

- -
var arr1 = [1, 2, [3, 4]];
-arr1.flat();
-
-//appianare array di un livello
-arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]
-
-//o
-const flatSingle = arr => [].concat(...arr);
-
- -
//abilitare appianamento a una certà profondità usando reduce e concat
-var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
-
-function flattenDeep(arr1) {
-   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
-}
-flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
-
- -
//appianamento profondo non ricorsivo usando uno stack
-var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
-function flatten(input) {
-  const stack = [...input];
-  const res = [];
-  while (stack.length) {
-    // rimozione valore dallo stack
-    const next = stack.pop();
-    if (Array.isArray(next)) {
-      // reinserimento degli elementi degli array, non modifica l'input originale
-      stack.push(...next);
-    } else {
-      res.push(next);
-    }
-  }
-  //reverse per ripristinare l'ordine originario
-  return res.reverse();
-}
-flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
-
- -
//appianamento profondo ricorsivo
-function flatten(array) {
-  var flattend = [];
-  !(function flat(array) {
-    array.forEach(function(el) {
-      if (Array.isArray(el)) flat(el);
-      else flattend.push(el);
-    });
-  })(array);
-  return flattend;
-}
-
- - - -

Specifiche

- - - - - - - - - - - - - - -
SpecificaStatoCommenti
-

Array.prototype.flat proposal

-
Finished (4)
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.flat")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/flatmap/index.html b/files/it/web/javascript/reference/global_objects/array/flatmap/index.html deleted file mode 100644 index 4397fd7c5d..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/flatmap/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Array.prototype.flatMap() -slug: Web/JavaScript/Reference/Global_Objects/Array/flatMap -translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap ---- -
{{JSRef}}
- -

Il metodo flatMap() prima mappa ogni elemento eseguendo la funzione passata come parametro, poi appiattisce il risultato in un nuovo array. Il comportamento è identico a una chiamata a  {{jsxref("Array.prototype.map","map()")}} seguita da un {{jsxref("Array.prototype.flat","flat()")}} con profondità 1, ma flatMap() in questo caso è la soluzione migliore perché è più efficente delle due chiamate separate.

- - - - - -

Sintassi

- -
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
-    // restituisci un elemento per il nuovo array
-}[, thisArg])
- -

Parametri

- -
-
callback
-
Funzione per produrre un elemento del nuovo Array, prevede a sua volta tre parametri: -
-
-
currentValue
-
L'elemento che si sta processando.
-
index{{optional_inline}}
-
L'indice dell'elemento corrente.
-
array{{optional_inline}}
-
L'array che si sta processando con map.
-
-
-
thisArg{{optional_inline}}
-
Valore usato come this mentre si esegue la callback.
-
- -

Risultato

- -

Un nuovo array i cui elementi sono il risultato della chiamata a callback, "appiattiti" ad una profondità di 1

- -

Descrizione

- -

Guarda {{jsxref("Array.prototype.map()")}} per una descrizione dettagliata della funzione callback. flatMap è identico a una chiamata a map seguita da una chiamata flat con una profondità di 1.

- -

Esempi

- -

map()flatMap()

- -
let arr1 = [1, 2, 3, 4];
-
-arr1.map(x => [x * 2]);
-// [[2], [4], [6], [8]]
-
-arr1.flatMap(x => [x * 2]);
-// [2, 4, 6, 8]
-
-// viene appiattito un solo elemento
-arr1.flatMap(x => [[x * 2]]);
-// [[2], [4], [6], [8]]
-
- -

Lo stesso risultato lo si può ottenere anche con la sola chiamata a map, di seguito è riportato un esempio migliore di uso di flatMap.

- -

Viene generata una lista di parole da una lista di frasi.

- -
let arr1 = ["it's Sunny in", "", "California"];
-
-arr1.map(x => x.split(" "));
-// [["it's","Sunny","in"],[""],["California"]]
-
-arr1.flatMap(x => x.split(" "));
-// ["it's","Sunny","in", "", "California"]
- -

Notare che, a differenza di map da solo, la lunghezza dell'output è diversa tra le due chiamate e in particolare il risultato di flatMap non avrà la stessa lunghezza dell'input.

- -

Aggiungere e rimuovere elementi durante l'esecuzione di map()

- -

flatMap può essere usato per aggiungere e rimuovere elementi durante l'esecuzione di map. In altre parole, offre la possibilità di mappare molti a molti (processando ogni input separatamente), anziché sempre uno a uno. In questo senso lavora come opposto di filter. Basta restituire un array con un solo elemento per mantenere l'oggetto invariato, un array con più elementi, invece, aggiungerà questi al risultato, un array vuoto per rimuovere l'elemento corrente.

- -
// Per rimuovere i numeri negativi e dividere i numeri dispari in un numero pari e un 1
-let a = [5, 4, -3, 20, 17, -33, -4, 18]
-//       |\  \  x   |  | \   x   x   |
-//      [4,1, 4,   20, 16, 1,       18]
-
-a.flatMap( (n) =>
-  (n < 0) ?      [] :
-  (n % 2 == 0) ? [n] :
-                 [n-1, 1]
-)
-
-// expected output: [4, 1, 4, 20, 16, 1, 18]
-
- -

Alternative

- -

reduce() and concat()

- -
var arr = [1, 2, 3, 4];
-
-arr.flatMap(x => [x, x * 2]);
-// si ottiene lo stesso risultato con
-arr.reduce((acc, x) => acc.concat([x, x * 2]), []);
-// [1, 2, 2, 4, 3, 6, 4, 8]
-
- -

Notare che questa soluzione non è efficente e non dovrebbe essere usata per array di grandi dimensioni: in ogni iterazione viene creato un nuovo array temporaneo che dovrà essere deallocato dal garbae collector, e copia gli elementi dall'array corrente (acc), in un nuovo array ad ogni iterazione invece di aggiungerli ad uno preesistente.

- - - -

Specifiche

- - - - - - - - - - -
Specifica
{{SpecName('ESDraft', '#sec-array.prototype.flatmap', 'Array.prototype.flatMap')}}
- -

Compatibilità browser

- -
- - -

{{Compat("javascript.builtins.Array.flatMap")}}

-
- -

Vedi anche

- - 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 deleted file mode 100644 index dbd4919852..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/foreach/index.html +++ /dev/null @@ -1,331 +0,0 @@ ---- -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 ---- -
{{JSRef}}
- -

Il metodo forEach() esegue una funzione fornita una volta per ogni elemento dell'array.

- -
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
- - - -

Sintassi

- -
arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
- -

Parametri

- -
-
callback
-
Funzione da eseguire per ciascun elemento, prendendo tre argomenti:
-
-
-
currentValue
-
L'elemento corrente in elaborazione nell'array.
-
index {{optional_inline}}
-
L'indice dell'elemento corrente in elaborazione nell'array.
-
array {{optional_inline}}
-
L'array a cui viene applicato forEach().
-
-
-
thisArg {{optional_inline}}
-
Valore da utilizzare come this quando si esegue callback.
-
- -

Descrizione

- -

forEach() esegue il callback 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).

- -

callback viene invocato con tre argomenti:

- - - -

Se viene fornito il parametro thisArg a forEach(), verrà utilizzato come valore this del callback. Altrimenti, il valore {{jsxref("undefined")}} sarà usato come valore this. Il valore this alla fine osservabile da callback è determinato secondo le consuete regole per determinare il this visto da una funzione.

- -

L'intervallo di elementi elaborati da forEach() viene impostato prima della prima chiamata del callback. Gli elementi aggiunti all'array dopo che la chiamata forEach() inizia non saranno calcolati da callback. Se i valori degli elementi esistenti dell'array vengono modificati, il valore passato a callback sarà il valore al momento in cui forEach() 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.

- -

forEach() esegue la funzione callback 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.

- -

forEach() non muta l'array su cui è chiamato (sebbene callback, se invocato, possa farlo).

- -
-

Non c'è modo di fermare o interrompere un loop forEach() se non lanciando un'eccezione. Se hai bisogno di un simile comportamento, il metodo forEach() è lo strumento sbagliato.

- -

La risoluzione anticipata può essere eseguita con:

- - - -

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.

-
- -

Esempi

- -

Convertire un loop for in forEach

- -
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);
-});
-
- -

Stampa del contenuto di un array

- -
-

Note: Per visualizzare il contenuto di un array nella console, puoi utilizzare console.table() che stamperà una versione formattata dell'array. L'esempio seguente illustra un altro modo per farlo, usando forEach().

-
- -

Il seguente codice logga una linea per ogni elemento in un array:

- -
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
-
- -

Usare thisArg

- -

Il seguente esempio (inventato) aggiorna le proprietà di un oggetto da ciascuna voce dell'array:

- -
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
-
- -

Poiché il parametro thisArg (this) viene fornito a forEach(), viene passato a callback ogni volta che viene richiamato, per essere utilizzato come valore this.

- -
-

Se si passa l'argomento della funzione utilizzando un'espressione della funzione a freccia il parametro thisArg può essere omesso poiché le funzioni a freccia associano in modo lessicale il valore {{jsxref("Operators/this", "this")}}.

-
- -

Una funzione di copia di oggetti

- -

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 Array.prototype.forEach() usando le funzioni di meta proprietà ECMAScript 5 Object.*.

- -
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
-
- -

Se l'array viene modificato durante l'iterazione, altri elementi potrebbero essere saltati.

- -

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. forEach() non esegue una copia dell'array prima di iterare.

- -
var words = ['uno', 'due', 'tre', 'quattro'];
-words.forEach(function(word) {
-  console.log(word);
-  if (word === 'due') {
-    words.shift();
-  }
-});
-// uno
-// due
-// quattro
-
- -

Appiattire un array

- -

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).

- -
/**
- * 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]
-
- -

Polyfill

- -

forEach() è 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 forEach() 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 callback.call() valuta il valore originale di {{jsxref("Function.prototype.call()")}}.

- -
// 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.
-  };
-}
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ESDraft')}}
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.forEach")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/from/index.html b/files/it/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index 83baed1267..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -tags: - - Array - - ECMAScript 2015 - - JavaScript - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -
{{JSRef}}
- -

Il metodo Array.from() crea una nuova istanza Array copiata superficialmente da un oggetto array-like o iterabile.

- -
{{EmbedInteractiveExample("pages/js/array-from.html")}}
- - - -

Sintassi

- -
Array.from(arrayLike[, mapFn[, thisArg]])
-
- -

Parametri

- -
-
arrayLike
-
Un oggetto array-like o iterabile da convertire in un array.
-
mapFn {{Optional_inline}}
-
Funzione map per chiamare su ogni elemento dell'array.
-
thisArg {{Optional_inline}}
-
Valore da utilizzare come this quando mapFn viene eseguita.
-
- -

Valore di ritorno

- -

Una nuova istanza {{jsxref("Array")}}.

- -

Descrizione

- -

Array.from() consente di creare Array da:

- - - -

Array.from() ha un parametro opzionale mapFn, che ti permette di eseguire una funzione {{jsxref("Array.prototype.map", "map")}} su ogni elemento dell'array (o dell'oggetto sottoclasse) che si sta creando. Più chiaramente, Array.from(obj, mapFn, thisArg) ha lo stesso risultato di Array.from(obj).map(mapFn, thisArg), tranne che non crea un array intermedio. Questo è particolarmente importante per alcune sottoclassi di array, come gli array tipizzati, poiché l'array intermedio avrebbe necessariamente valori troncati per adattarsi al tipo appropriato.

- -

La proprietà length del metodo from() è 1.

- -

In ES2015, la sintassi della classe consente la sottoclassificazione di entrambe le classi predefinite e definite dall'utente; di conseguenza, i metodi statici come Array.from sono "ereditati" dalle sottoclassi di Array e creano nuove istanze della sottoclasse, non Array.

- -

Esempi

- -

Array da una String

- -
Array.from('foo');
-// ["f", "o", "o"]
- -

Array da un Set

- -
var s = new Set(['foo', window]);
-Array.from(s);
-// ["foo", window]
- -

Array da una Map

- -
var m = new Map([[1, 2], [2, 4], [4, 8]]);
-Array.from(m);
-// [[1, 2], [2, 4], [4, 8]]
-
-var mapper = new Map([['1', 'a'], ['2', 'b']]);
-Array.from(mapper.values());
-// ['a', 'b'];
-
-Array.from(mapper.keys());
-// ['1', '2'];
-
- -

Array di un oggetto Array-like (arguments)

- -
function f() {
-  return Array.from(arguments);
-}
-
-f(1, 2, 3);
-
-// [1, 2, 3]
- -

Utilizzo delle funzioni a freccia e Array.from

- -
// Utilizzando una funzione freccia come funzione map
-// per manipolare gli elementi
-Array.from([1, 2, 3], x => x + x);
-// [2, 4, 6]
-
-
-// Genera una sequenza di numeri
-// Poiché l'array è inizializzato con `undefined` su ogni posizione,
-// il valore di `v` sotto sarà `undefined`
-Array.from({length: 5}, (v, i) => i);
-// [0, 1, 2, 3, 4]
-
- -

Generatore di sequenze (range)

- -
// Funzione del generatore di sequenze (comunemente denominata "range", ad esempio Clojure, PHP ecc.)
-const range = (start, stop, step) => Array.from({ length: (stop - start) / step }, (_, i) => start + (i * step));
-
-// Genera numeri range 0..4
-range(0, 5, 1);
-// [0, 1, 2, 3, 4]
-
-// Genera l'alfabeto usando Array.from facendolo usare come sequenza
-range('A'.charCodeAt(0), 'Z'.charCodeAt(0) + 1, 1).map(x => String.fromCharCode(x));
-// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
-
- -

Polyfill

- -

Array.from è stato aggiunto allo standard ECMA-262 nella sesta edizione (ES2015); 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 Array.from in implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 6a edizione, assumendo che Object e TypeError abbiano i loro valori originali e che callback.call valuti il valore originale di {{jsxref("Function.prototype.call")}}. Inoltre, poiché i veri iterabili non possono essere polyfilled, questa implementazione non supporta iterables generici come definito nella sesta edizione di ECMA-262.

- -
// Production steps of ECMA-262, Edition 6, 22.1.2.1
-if (!Array.from) {
-  Array.from = (function () {
-    var toStr = Object.prototype.toString;
-    var isCallable = function (fn) {
-      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
-    };
-    var toInteger = function (value) {
-      var number = Number(value);
-      if (isNaN(number)) { return 0; }
-      if (number === 0 || !isFinite(number)) { return number; }
-      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
-    };
-    var maxSafeInteger = Math.pow(2, 53) - 1;
-    var toLength = function (value) {
-      var len = toInteger(value);
-      return Math.min(Math.max(len, 0), maxSafeInteger);
-    };
-
-    // The length property of the from method is 1.
-    return function from(arrayLike/*, mapFn, thisArg */) {
-      // 1. Let C be the this value.
-      var C = this;
-
-      // 2. Let items be ToObject(arrayLike).
-      var items = Object(arrayLike);
-
-      // 3. ReturnIfAbrupt(items).
-      if (arrayLike == null) {
-        throw new TypeError('Array.from requires an array-like object - not null or undefined');
-      }
-
-      // 4. If mapfn is undefined, then let mapping be false.
-      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
-      var T;
-      if (typeof mapFn !== 'undefined') {
-        // 5. else
-        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
-        if (!isCallable(mapFn)) {
-          throw new TypeError('Array.from: when provided, the second argument must be a function');
-        }
-
-        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
-        if (arguments.length > 2) {
-          T = arguments[2];
-        }
-      }
-
-      // 10. Let lenValue be Get(items, "length").
-      // 11. Let len be ToLength(lenValue).
-      var len = toLength(items.length);
-
-      // 13. If IsConstructor(C) is true, then
-      // 13. a. Let A be the result of calling the [[Construct]] internal method
-      // of C with an argument list containing the single item len.
-      // 14. a. Else, Let A be ArrayCreate(len).
-      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
-
-      // 16. Let k be 0.
-      var k = 0;
-      // 17. Repeat, while k < len… (also steps a - h)
-      var kValue;
-      while (k < len) {
-        kValue = items[k];
-        if (mapFn) {
-          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
-        } else {
-          A[k] = kValue;
-        }
-        k += 1;
-      }
-      // 18. Let putStatus be Put(A, "length", len, true).
-      A.length = len;
-      // 20. Return A.
-      return A;
-    };
-  }());
-}
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}{{Spec2('ES2015')}}Definizione iniziale.
- -

Compatibilità con i browser

- - - -

{{Compat("javascript.builtins.Array.from")}}

- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/includes/index.html b/files/it/web/javascript/reference/global_objects/array/includes/index.html deleted file mode 100644 index 04dc817974..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/includes/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Array.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/Array/includes -translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes ---- -
{{JSRef}}
- -

Il metodo includes() determina se un array include un certo elemento, ritornando truefalse a seconda del caso

- -

Sintassi

- -
var boolean = array.includes(searchElement[, fromIndex])
- -

Parametri

- -
-
searchElement
-
L'elemento da cercare.
-
fromIndex
-
Opzionale. La posizione nell'array da cui partire per cercare l'elemento searchElement. Un valore negativo ricerca dal valore di array.length + fromIndex in maniera ascendente. Il valore di default è 0.
-
- -

Valore di ritorno

- -

Un {{jsxref("Boolean")}}.

- -

Examples

- -
[1, 2, 3].includes(2);     // true
-[1, 2, 3].includes(4);     // false
-[1, 2, 3].includes(3, 3);  // false
-[1, 2, 3].includes(3, -1); // true
-[1, 2, NaN].includes(NaN); // true
-
- -

Polyfill

- -
if (!Array.prototype.includes) {
-  Array.prototype.includes = function(searchElement /*, fromIndex*/) {
-    'use strict';
-    if (this == null) {
-      throw new TypeError('Array.prototype.includes called on null or undefined');
-    }
-
-    var O = Object(this);
-    var len = parseInt(O.length, 10) || 0;
-    if (len === 0) {
-      return false;
-    }
-    var n = parseInt(arguments[1], 10) || 0;
-    var k;
-    if (n >= 0) {
-      k = n;
-    } else {
-      k = len + n;
-      if (k < 0) {k = 0;}
-    }
-    var currentElement;
-    while (k < len) {
-      currentElement = O[k];
-      if (searchElement === currentElement ||
-         (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
-        return true;
-      }
-      k++;
-    }
-    return false;
-  };
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support -

{{CompatChrome(47)}}

-
43{{CompatNo}}14279+349
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}} -

{{CompatChrome(47)}}

-
43{{CompatNo}}349 -

{{CompatChrome(47)}}

-
-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/index.html b/files/it/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 844d1baf00..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,480 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

Sommario

- -

L'oggetto Array di JavaScript  è un oggetto globale che è utilizzato nella costruzione di array; che sono oggetti di alto-livello del tipo lista.

- -

Creare un Array

- -
var fruits = ["Apple", "Banana"];
-
-console.log(fruits.length);
-// 2
-
- -

Accedere (index into) ad un Array item

- -
var first = fruits[0];
-// Apple
-
-var last = fruits[fruits.length - 1];
-// Banana
-
- -

Loop in un  Array

- -
fruits.forEach(function (item, index, array) {
-  console.log(item, index);
-});
-// Apple 0
-// Banana 1
-
- -

Aggiungere alla fine di  un Array

- -
var newLength = fruits.push("Orange");
-// ["Apple", "Banana", "Orange"]
-
- -

Rimuovere dalla fine di un Array

- -
var last = fruits.pop(); // remove Orange (from the end)
-// ["Apple", "Banana"];
-
- -

Rimuovere dall'inizio di un Array

- -
var first = fruits.shift(); // remove Apple from the front
-// ["Banana"];
-
- -

Aggiungere al'inizio di un Array

- -
var newLength = fruits.unshift("Strawberry") // add to the front
-// ["Strawberry", "Banana"];
-
- -

Trovare l'indice di un elemento nell'Array

- -
fruits.push("Mango");
-// ["Strawberry", "Banana", "Mango"]
-
-var pos = fruits.indexOf("Banana");
-// 1
-
- -

Rimuovere un elemento tramite la Posizione dell'Indice

- -
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
-// ["Strawberry", "Mango"]
-
- -

Copiare un Array

- -
var shallowCopy = fruits.slice(); // this is how to make a copy
-// ["Strawberry", "Mango"]
-
- -

Sintassi

- -
[element0, element1, ..., elementN]
-new Array(element0, element1[, ...[, elementN]])
-new Array(arrayLength)
- -
-
elementN
-
Un array JavaScript è inizializzato con gli elementi dati, eccetto nel caso in cui un argomento singolo è passato al costruttore dell'Array e l'argomento è un numero. (Vedere sotto.) Notare che questo caso speciale si applica solo agli array JavaScript creati con il costruttore Array, non array literals creati con la sintassi a parentesi.
-
arrayLength
-
Se l'unico argomento passato al costruttore Array è un integer tra  0 e 232-1 (inclusivo), questo restituisce un nuovo array JavaScript con la lunghezza settata su quel numero. Se l'argomento è un qualsiasi altro numero, un eccezione {{jsxref("Global_Objects/RangeError", "RangeError")}} è lanciata.
-
- -

Descrizione

- -

Gli Array sono come oggetti di tipo lista il cui prototipo ha metodi per performare operazioni trasversali e di mutazione. Nè la lunghezza di un array JavaScript o i tipi dei suoi elementi sono fissati. Poichè la grandezza della lunghezza di un array cresce o diminuisce in qualsiasi momento, gli array JavaScript non danno garanzia di essere compatti; questo dipende da come il programmatore sceglie di usarli. In generale, queste sono caratteristiche convenienti; ma se tali  caratteristiche non fossero desiderabili per un utilizzo particolare, si potrebbe considerare di utilizzare i typed arrays.

- -

Alcuni pensano che non si dovrebbe un utilizzare un array come un associative array. In ogni  caso, si può utilizzare un semplice {{jsxref("Global_Objects/Object", "objects")}} invece, con i suoi avvertimenti. Vedere il post Lightweight JavaScript dictionaries with arbitrary keys come esempio.

- -

Accedere ad elementi di  array 

- -

Gli array JavaScript sono indicizzati a zero: il primo elemento di un array è all'indice 0, e l'ultimo elemento è all'indice uguale al valore della proprietà dell'array {{jsxref("Array.length", "length")}}  meno 1. Usare un numero di indice invalido restituisce undefined.

- -
var arr = ['this is the first element', 'this is the second element'];
-console.log(arr[0]);              // logs 'this is the first element'
-console.log(arr[1]);              // logs 'this is the second element'
-console.log(arr[arr.length - 1]); // logs 'this is the second element'
-
- -

Gli elementi dell'Array sono proprietà dell'oggetto allo stesso modo che toString è una proprietà, ma provare ad accedere ad un elemento di un array come segue, lancia un errore di sintassi, poichè la proprietà del nome non è valida:

- -
console.log(arr.0); // a syntax error
-
- -

Non c'è niente di speciale riguardo gli array JavaScript e la proprietà che causa questo. Le proprietà JavaScript che iniziano con un numero non possono essere referenziate con la notazione punto: e vi si deve accedere usando la notazione parentesi quadre. Per esempio, se si avesse un oggetto con una proprietà chiamata '3d', la si potrebbe referenziare solamente utilizzando la notazione parentesi quadre. E.g.:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0);   // a syntax error
-console.log(years[0]);  // works properly
-
- -
renderer.3d.setTexture(model, 'character.png');     // a syntax error
-renderer['3d'].setTexture(model, 'character.png');  // works properly
-
- -

Notare che nell'esempio 3d, '3d' doveva essere messo tra virgolette. E' possibile mettere tra virgolette anche gli indici dell'array JavaScript (e.g., years['2'] invece di years[2]), anche se non necessario. Il 2 in years[2] è costretto in una stringa dal motore di JavaScript attraverso una implicita conversione toString. E' per questa ragione che  '2' e '02' riferirebbero a due differenti slot nell'oggetto years ed il seguente esempio potrebbe essere true:

- -
console.log(years['2'] != years['02']);
-
- -

Ugualmente, alle proprietà di oggetti che sono parole riservate(!) vi si può accedere come string literals in notazione parentesi quadrate (ma anche in notazione punto a partire dalla versione  40.0a2 di firefox):

- -
var promise = {
-  'var'  : 'text',
-  'array': [1, 2, 3, 4]
-};
-
-console.log(promise['var']);
- -

Relzione tra length e proprietà numeriche

- -

Una proprietà di un array JavaScript {{jsxref("Array.length", "length")}} e proprietà numeriche sono connesse. Molti dei metodi integrati di array(e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) tengono in conto del valore della proprietà dell'array {{jsxref("Array.length", "length")}} quando sono chiamati. Altri metodi(e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) risultano nell'aggiornamento della proprietà{{jsxref("Array.length", "length")}} dell'array.

- -
var fruits = [];
-fruits.push('banana', 'apple', 'peach');
-
-console.log(fruits.length); // 3
-
- -

Quando si setta una proprietà su un array JavaScript, quando la proprietà è un valido indice di array e quell'iindice è al di fuori dei limiti dell'array, il motore aggiornerà la proprietà {{jsxref("Array.length", "length")}} in accordo:

- -
fruits[5] = 'mango';
-console.log(fruits[5]); // 'mango'
-console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
-console.log(fruits.length); // 6
-
- -

Aumentando{{jsxref("Array.length", "length")}}.

- -
fruits.length = 10;
-console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
-console.log(fruits.length); // 10
-
- -

Diminuendo la proprietà {{jsxref("Array.length", "length")}}, comunque cancella gli elementi.

- -
fruits.length = 2;
-console.log(Object.keys(fruits)); // ['0', '1']
-console.log(fruits.length); // 2
-
- -

La spiegazione è ampliata nella pagina{{jsxref("Array.length")}}.

- -

Creare un array utilizzando il risultato di un match

- -

Il risultato di una corrispondenza tra una espressione regolare e una stringa può creare un array JavaScript. Tale array ha proprietà ed elementi che provvedono informazioni riguardo il match. Questo tipo di array è restituito da {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, e {{jsxref("String.replace")}}. Per aiutare a spiegare queste proprietà ed elementi, vedere l'esempio seguente e fare riferimento alla tavola sottostante:

- -
// Match one d followed by one or more b's followed by one d
-// Remember matched b's and the following d
-// Ignore case
-
-var myRe = /d(b+)(d)/i;
-var myArray = myRe.exec('cdbBdbsbz');
-
- -

Le proprietà ed elementi restituiti da questo match sono le seguenti:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property/ElementDescriptionExample
inputUna proprietà read-only che riflette la stinga originale verso la quale l'espressione irregolare era stata abbinata.cdbBdbsbz
indexUna proprietà read-only su indice base-zeroindex dell'abbinamento nella stringa.1
[0]Un elemento read-only che specifica gli ultimi caratteri abbinati.dbBd
[1], ...[n]Elementi read-only  che specificano gli abbinamenti di sottostringa in parentesi, se inclusi nella espressione regolare. Il numero di possibili sottostringhe in parentesi è illimitato.[1]: bB
- [2]: d
- -

Proprietà

- -
-
Array.length
-
Il costruttore della proprietà lunghezza  Array il cui valore è 1.
-
{{jsxref("Array.@@species", "get Array[@@species]")}}
-
La funzione del costruttore che è usata per creare oggetti derivati.
-
{{jsxref("Array.prototype")}}
-
Permette l'addizione  di proprietà a tutti gli oggetti array.
-
- -

Metodi

- -
-
{{jsxref("Array.from()")}} {{experimental_inline}}
-
Crea una nuova istanza Array da un oggetto del tipo array o iterabile.
-
{{jsxref("Array.isArray()")}}
-
Restituisce true se una variabile è un array, altrimenti false.
-
{{jsxref("Array.observe()")}} {{experimental_inline}}
-
In modo asincrono osserva i cambiamenti agli Arrays, come{{jsxref("Object.observe()")}} per gli oggetti. Provvede un flusso di cambiamenti in ordine di occorrenza.
-
{{jsxref("Array.of()")}} {{experimental_inline}}
-
Crea una nuova istanza Array con un variabile numero di argomenti, nonostante il numero o i tipi di argomenti.
-
- -

Istanze di Array 

- -

Tutte le istanze di Array ereditano da {{jsxref("Array.prototype")}}. L'oggetto prototype del costruttore Array può essere modificato per influenzare tutte le istanze di  Array.

- -

Proprietà

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
- -

Metodi

- -

Metodi mutatori

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
- -

Metodi per accedere

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
- -

Metodi di iterazione

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}} 
- -

Metodi generici Array 

- -
-

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

-
- -

A volte si vorrebbe applicare metodi di array alle stringhe o altri oggetti del tipo array (come {{jsxref("Functions/arguments", "arguments", "", 1)}}). Facendo ciò, si tratta una stringa come un array di caratteri(o altrimenti trattare un non array come array). Per esempio, per controllare che ogni carattere nella variabile str sia una lettera, si scriverebbe:

- -
function isLetter(character) {
-  return character >= 'a' && character <= 'z';
-}
-
-if (Array.prototype.every.call(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

Tale notazione è dispersiva e JavaScript 1.6 ha introdotto un generico shorthand:

- -
if (Array.every(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("Global_Objects/String", "String")}}.

- -

Queste no fanno parte dello standard ECMAScript (anche se ES2015 {{jsxref("Array.from()")}} può essere utilizzato per raggingere tale scopo). Ciò che segue è un aiuto per permetterene l'utilizzo in tutti i browser:

- -
// Assumes Array extras already present (one may use polyfills for these as well)
-(function() {
-  'use strict';
-
-  var i,
-    // We could also build the array of methods with the following, but the
-    //   getOwnPropertyNames() method is non-shimable:
-    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
-    //   return typeof Array[methodName] === 'function'
-    // });
-    methods = [
-      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
-      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
-      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
-      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
-      'values', 'copyWithin', 'includes'
-    ],
-    methodCount = methods.length,
-    assignArrayGeneric = function(methodName) {
-      if (!Array[methodName]) {
-        var method = Array.prototype[methodName];
-        if (typeof method === 'function') {
-          Array[methodName] = function() {
-            return method.call.apply(method, arguments);
-          };
-        }
-      }
-    };
-
-  for (i = 0; i < methodCount; i++) {
-    assignArrayGeneric(methods[i]);
-  }
-}());
-
- -

Esempi

- -

Creare un array

- -

Il seguente esempio crea un array, msgArray, con una lunghezza di 0, poi assegna valori a  msgArray[0] e msgArray[99], cambiando la lunghezza dell'array a 100.

- -
var msgArray = [];
-msgArray[0] = 'Hello';
-msgArray[99] = 'world';
-
-if (msgArray.length === 100) {
-  console.log('The length is 100.');
-}
-
- -

Creare un array bidimensionale

- -

Ciò che segue crea una scacchiera come un array bidiensionale di stringhe. La prima mossa è fatta copiando la 'p' in (6,4) in (4,4). La vecchia posizione (6,4) è resa bianca.

- -
var board = [
-  ['R','N','B','Q','K','B','N','R'],
-  ['P','P','P','P','P','P','P','P'],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  ['p','p','p','p','p','p','p','p'],
-  ['r','n','b','q','k','b','n','r'] ];
-
-console.log(board.join('\n') + '\n\n');
-
-// Move King's Pawn forward 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
-
- -

Ecco l'output:

- -
R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
-p,p,p,p,p,p,p,p
-r,n,b,q,k,b,n,r
-
-R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , ,p, , ,
- , , , , , , ,
-p,p,p,p, ,p,p,p
-r,n,b,q,k,b,n,r
-
- -

Specificazioni

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}Nuovi metodi aggiunti: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES2015', '#sec-array-objects', 'Array')}}{{Spec2('ES2015')}}Nuovi metodi aggiunti: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
- -

Compatibilità Browser 

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Vedere anche:

- - diff --git a/files/it/web/javascript/reference/global_objects/array/indexof/index.html b/files/it/web/javascript/reference/global_objects/array/indexof/index.html deleted file mode 100644 index 658957c67d..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/indexof/index.html +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Array.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf -tags: - - Array - - JavaScript - - Prototype - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf ---- -
{{JSRef}}
- -

Il metodo indexOf() restituisce il primo indice in cui è possibile trovare un determinato elemento nell'array o -1 se non è presente.

- -
-

Note: Per il metodo String, consultare {{jsxref("String.prototype.indexOf()")}}.

-
- -
{{EmbedInteractiveExample("pages/js/array-indexof.html")}}
- - - -

Sintassi

- -
arr.indexOf(searchElement[, fromIndex])
- -

Parametri

- -
-
searchElement
-
Elemento da localizzare nell'array.
-
fromIndex {{optional_inline}}
-
L'indice per iniziare la ricerca. Se l'indice è maggiore o uguale alla lunghezza dell'array, viene restituito -1, il che significa che l'array non verrà cercato. Se il valore dell'indice fornito è un numero negativo, viene preso come offset dalla fine dell'array. Nota: se l'indice fornito è negativo, l'array viene comunque ricercato da fronte a retro. Se l'indice fornito è 0, verrà cercato l'intero array. Predefinito: 0 (viene cercato l'intero array).
-
- -

Valore di ritorno

- -

Il primo indice dell'elemento nell'array; -1 se non trovato.

- -

Descrizione

- -

indexOf() compara searchElement con gli elementi dell'array usando strict equality (lo stesso metodo utilizzato dall'operatore === o triple-equals).

- -

Esempi

- -

Usare indexOf()

- -

Nell'esempio seguente viene utilizzato indexOf() per individuare i valori in un array.

- -
var array = [2, 9, 9];
-array.indexOf(2);     // 0
-array.indexOf(7);     // -1
-array.indexOf(9, 2);  // 2
-array.indexOf(2, -1); // -1
-array.indexOf(2, -3); // 0
-
- -

Trovare tutte le occorrenze di un elemento

- -
var indices = [];
-var array = ['a', 'b', 'a', 'c', 'a', 'd'];
-var element = 'a';
-var idx = array.indexOf(element);
-while (idx != -1) {
-  indices.push(idx);
-  idx = array.indexOf(element, idx + 1);
-}
-console.log(indices);
-// [0, 2, 4]
-
- -

Trovare se un elemento esiste nell'array o meno ed aggiornare l'array

- -
function updateVegetablesCollection (veggies, veggie) {
-    if (veggies.indexOf(veggie) === -1) {
-        veggies.push(veggie);
-        console.log('New veggies collection is : ' + veggies);
-    } else if (veggies.indexOf(veggie) > -1) {
-        console.log(veggie + ' already exists in the veggies collection.');
-    }
-}
-
-var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
-
-updateVegetablesCollection(veggies, 'spinach');
-// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
-updateVegetablesCollection(veggies, 'spinach');
-// spinach already exists in the veggies collection.
-
- -

Polyfill

- -

indexOf() è stato aggiunto allo standard ECMA-262 nella quinta edizione; in quanto tale potrebbe non essere presente in tutti i browser. Puoi aggirare questo problema utilizzando il seguente codice all'inizio degli script. Questo ti permetterà di usare indexOf() quando non c'è ancora alcun supporto nativo. Questo algoritmo corrisponde a quello specificato in ECMA-262, 5a edizione, assumendo che {{jsxref("Global_Objects/TypeError", "TypeError")}} e {{jsxref("Math.abs()")}} abbiano i loro valori originali.

- -
if (!Array.prototype.indexOf)  Array.prototype.indexOf = (function(Object, max, min){
-  "use strict";
-  return function indexOf(member, fromIndex) {
-    if(this===null||this===undefined)throw TypeError("Array.prototype.indexOf called on null or undefined");
-
-    var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len);
-    if (i < 0) i = max(0, Len+i); else if (i >= Len) return -1;
-
-    if(member===void 0){ for(; i !== Len; ++i) if(that[i]===void 0 && i in that) return i; // undefined
-    }else if(member !== member){   for(; i !== Len; ++i) if(that[i] !== that[i]) return i; // NaN
-    }else                           for(; i !== Len; ++i) if(that[i] === member) return i; // all else
-
-    return -1; // if the value was not found, then return -1
-  };
-})(Object, Math.max, Math.min);
-
- -

Tuttavia, se sei più interessato a tutti i piccoli bit tecnici definiti dallo standard ECMA e meno preoccupati per le prestazioni o la concisione, potresti trovare questo polifratura più descrittivo per essere più utile.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.14
-// Reference: http://es5.github.io/#x15.4.4.14
-if (!Array.prototype.indexOf) {
-  Array.prototype.indexOf = function(searchElement, fromIndex) {
-
-    var k;
-
-    // 1. Let o be the result of calling ToObject passing
-    //    the this value as the argument.
-    if (this == null) {
-      throw new TypeError('"this" is null or not defined');
-    }
-
-    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 len is 0, return -1.
-    if (len === 0) {
-      return -1;
-    }
-
-    // 5. If argument fromIndex was passed let n be
-    //    ToInteger(fromIndex); else let n be 0.
-    var n = fromIndex | 0;
-
-    // 6. If n >= len, return -1.
-    if (n >= len) {
-      return -1;
-    }
-
-    // 7. If n >= 0, then Let k be n.
-    // 8. Else, n<0, Let k be len - abs(n).
-    //    If k is less than 0, then let k be 0.
-    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
-
-    // 9. Repeat, while k < len
-    while (k < len) {
-      // 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
-      //    i.  Let elementK be the result of calling the Get
-      //        internal method of o with the argument ToString(k).
-      //   ii.  Let same be the result of applying the
-      //        Strict Equality Comparison Algorithm to
-      //        searchElement and elementK.
-      //  iii.  If same is true, return k.
-      if (k in o && o[k] === searchElement) {
-        return k;
-      }
-      k++;
-    }
-    return -1;
-  };
-}
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}} 
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.indexOf")}}

-
- -

Note di compatibilità

- - - -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/isarray/index.html b/files/it/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index d7aaf864bf..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Array - - ECMAScript 5 - - JavaScript - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -
{{JSRef}}
- -

Il metodo Array.isArray() determina se il valore passato è un {{jsxref("Array")}}.

- -
Array.isArray([1, 2, 3]);  // true
-Array.isArray({foo: 123}); // false
-Array.isArray('foobar');   // false
-Array.isArray(undefined);  // false
-
- -

Sintassi

- -
Array.isArray(value)
- -

Parametri

- -
-
value
-
Il valore da verificare.
-
- -

Valore di ritorno

- -

true se il valore è un {{jsxref("Array")}}; altrimenti, false.

- -

Descrizione

- -

Se il valore è un {{jsxref("Array")}}, viene ritornato true; altrimenti viene ritornato false.

- -

Vedi l'articolo “Determining with absolute accuracy whether or not a JavaScript object is an array” per maggiori dettagli. Data un'istanza {{jsxref("TypedArray")}}, viene ritornato sempre false.

- -

Esempi

- -
// tutte le seguenti chiamate ritornano true
-Array.isArray([]);
-Array.isArray([1]);
-Array.isArray(new Array());
-Array.isArray(new Array('a', 'b', 'c', 'd'));
-Array.isArray(new Array(3));
-// Fatto poco noto: Array.prototype stesso è un array:
-Array.isArray(Array.prototype);
-
-// tutte le seguenti chiamate ritornano false
-Array.isArray();
-Array.isArray({});
-Array.isArray(null);
-Array.isArray(undefined);
-Array.isArray(17);
-Array.isArray('Array');
-Array.isArray(true);
-Array.isArray(false);
-Array.isArray(new Uint8Array(32));
-Array.isArray({ __proto__: Array.prototype });
-
- -

instanceof vs isArray

- -

Quando si verifica l'istanza ArrayArray.isArray è preferito su instanceof perché funziona attraverso gli iframes.

- -
var iframe = document.createElement('iframe');
-document.body.appendChild(iframe);
-xArray = window.frames[window.frames.length-1].Array;
-var arr = new xArray(1,2,3); // [1,2,3]
-
-// Verifica corretta dell'array
-Array.isArray(arr);  // true
-// Considerato dannoso, perché non funziona attraverso iframe
-arr instanceof Array; // false
-
- -

Polyfill

- -

L'esecuzione del seguente codice prima di qualsiasi altro codice creerà Array.isArray() se non è nativamente disponibile.

- -
if (!Array.isArray) {
-  Array.isArray = function(arg) {
-    return Object.prototype.toString.call(arg) === '[object Array]';
-  };
-}
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}}
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.isArray")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/join/index.html b/files/it/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 8483c817ac..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - Array - - JavaScript - - Prototype - - Referenza - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

Il metodo join() unisce tutti gli elementi di un array (o di un array di oggetti) in una stringa che viene restituita.

- -
var a = ['Wind', 'Rain', 'Fire'];
-a.join();    // 'Wind,Rain,Fire'
-a.join('-'); // 'Wind-Rain-Fire'
- -

Sintassi

- -
arr.join()
-arr.join(separatore)
- -

Parametri

- -
-
separatore {{optional_inline}}
-
Specifica una stringa che separa ogni coppia di elementi adiacenti dell'array. Il separatore è trasformato in una stringa, se necessario. Se omesso, gli elementi dell'array saranno separati da una virgola (","). Se il separatore è una stringa vuota, tutti gli elementi sono uniti senza alcun carattere intemedio.
-
- -

Valore di risposta

- -

Una stringa con tutti con tutti gli elementi dell'array uniti. Se arr.length è 0, viene restituita una stringa vuota.

- -

Descrizione

- -

Le stringe ottenute dalla conversione di tutti gli elementi dell'array sono unite in un unica stringa.

- -
-

Se un elemento è undefinednull, sarà convertito in una stringa vuota.

-
- -

Esempi

- -

Quattro modi per concatenare un array

- -

Il seguente esempio crea un array, a, con tre elementi, quindi unisce gli elementi dell'array quattro volte: usando l'operatore di default, poi una virgola e uno spazio, poi un più e infine una stringa vuota.

- -
var a = ['Wind', 'Rain', 'Fire'];
-a.join();      // 'Wind,Rain,Fire'
-a.join(', ');  // 'Wind, Rain, Fire'
-a.join(' + '); // 'Wind + Rain + Fire'
-a.join('');    // 'WindRainFire'
- -

Unione di un oggetto di tipo array

- -

Il seguente esempio unisce un oggetto di tipo array (arguments), chiamando {{jsxref("Function.prototype.call")}} con Array.prototype.join.

- -
function f(a, b, c) {
-  var s = Array.prototype.join.call(arguments);
-  console.log(s); // '1,a,true'
-}
-f(1, 'a', true);
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificheStatoCommenti
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementato in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
- -

Compatibilità browser

- -
- - -

{{Compat("javascript.builtins.Array.join")}}

-
- -

Guarda anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/keys/index.html b/files/it/web/javascript/reference/global_objects/array/keys/index.html deleted file mode 100644 index 78212d221f..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/keys/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: Array.prototype.keys() -slug: Web/JavaScript/Reference/Global_Objects/Array/keys -translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys ---- -
{{JSRef}}
- -

Il metodo keys() ritorna un nuovo oggetto Array Iterator contenente le chiavi di ogni indice dell'array.

- -
var arr = ['a', 'b', 'c'];
-var iterator = arr.keys();
-
-console.log(iterator.next()); // { value: 0, done: false }
-console.log(iterator.next()); // { value: 1, done: false }
-console.log(iterator.next()); // { value: 2, done: false }
-console.log(iterator.next()); // { value: undefined, done: true }
-
- -

Sintassi

- -
arr.keys()
- -

Valore di ritorno

- -

Un nuovo oggetto {{jsxref("Array")}}.

- -

Esempi

- -

I Key iterator non ignorano gli elementi vuoti

- -
var arr = ['a', , 'c'];
-var sparseKeys = Object.keys(arr);
-var denseKeys = [...arr.keys()];
-console.log(sparseKeys); // ['0', '2']
-console.log(denseKeys);  // [0, 1, 2]
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.keys")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html deleted file mode 100644 index c4170455f6..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -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 ---- -
{{JSRef}}
- -

Il metodo lastIndexOf() 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 fromIndex.

- -
{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}
- - - -

Sintassi

- -
arr.lastIndexOf(searchElement)
-arr.lastIndexOf(searchElement, fromIndex)
-
- -

Parametri

- -
-
searchElement
-
Elemento da trovare nell' array.
-
fromIndex {{optional_inline}}
-
L'indice da cui iniziare a cercare al contrario. Di defaults la lunghezza dell' array meno uno (arr.length - 1), 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.
-
- -

Valori restituiti

- -

L'ultimo indice dell' elemento nell' array; -1 se non trovato.

- -

Descrizione

- -

lastIndexOf compara searchElement a gli elementi dell' array usando strict equality (lo stesso metodo usato ===, o triple-equals, operator).

- -

Esempi

- -

Utilizzo di lastIndexOf

- -

L'esempio seguente usa lastIndexOf per trovare i valori in un array.

- -
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
-
- -

Trovare tutte le posizioni di un elemento

- -

Il seguente esempio usa lastIndexOf per trovare tutti gli elementi nell' array, usando {{jsxref("Array.prototype.push", "push")}} per essere aggiunti in un array come vengono trovati.

- -
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]
-
- -

Nota che non abbiamo considerato idx == 0perchè l'elemento sarà sempre troavto indipendemente da il parametro fromIndex se è il primo elemento dell'array. TQuesto è diveso dal metodo {{jsxref("Array.prototype.indexOf", "indexOf")}}.

- -

Polyfill

- -

lastIndexOf è 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 lastIndexOf 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.

- -
// 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;
-  };
-}
-
- -

Ancora, nota che questa implementazione mira alla compatibilità assoluta con lastIndexOf in Firefox e SpiderMonkey JavaScript engine, includendo alcuni casi che sono considerati estremi. ISe hai intenzione di usare questo in applicazioni reali, potresti calcolare from con un codice meno complicato se ignori questi casi.

- -

Descrizione

- - - - - - - - - - - - - - - - - - - - - - - - -
DescrizioneStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ESDraft')}} 
- -

Compatibilità con il browser

- -
- - -

{{Compat("javascript.builtins.Array.lastIndexOf")}}

-
- -

Note di compatibilità

- - - -

Guarda anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/length/index.html b/files/it/web/javascript/reference/global_objects/array/length/index.html deleted file mode 100644 index a36a6b5204..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/length/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.length -slug: Web/JavaScript/Reference/Global_Objects/Array/length -translation_of: Web/JavaScript/Reference/Global_Objects/Array/length ---- -
{{JSRef}}
- -
La proprieta' length setta o restituisce il numero di elementi in un array. E' un intero a 32 bit, sempre maggiore del piu' grande indice dell'array.
- -
 
- -
var items = ['shoes', 'shirts', 'socks', 'sweaters'];
-items.length;
-
-// returns 4
- -

Descrizione

- -

Puoi impostare la proprietà length di un array per troncare o estendere l'array stesso.

- -
var a = [1,2,3];
-a.length=2;
-// a is now [1, 2]
-
-a.length = 10
-// a is now [1, 2, undefined × 8]
-
- -

 

- -

Esempi

- -

Iterare su un array

- -

Nel seguente esempio, l'array numbers viene iterarato e ciascun elemento viene moltiplicato per 2.

- -
var numbers = [1, 2, 3, 4, 5];
-var length = numbers.length;
-for (var i = 0; i < length; i++) {
-  numbers[i] *= 2;
-}
-// numbers is now [2, 4, 6, 8, 10]
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificheStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
- -

Compatibilità

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

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 ---- -
{{JSRef}}
- -

Il metodo map() crea un nuovo array con i risultati della chiamata di una funzione fornita su ogni elemento dell'array chiamante.

- -
{{EmbedInteractiveExample("pages/js/array-map.html")}}
- - - -

Sintassi

- -
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
-    // Ritorna un elemento per new_array
-}[, thisArg])
- -

Parametri

- -
-
callback
-
Funzione che produce un elemento del nuovo array, prendendo tre argomenti: -
-
 
-
currentValue
-
L'elemento corrente in elaborazione nell'array.
-
index{{optional_inline}}
-
L'indice dell'elemento corrente in elaborazione nell'array.
-
array{{optional_inline}}
-
L'array a cui viene applicato map.
-
-
-
thisArg{{optional_inline}}
-
Valore da utilizzare come this quando viene eseguito callback.
-
- -

Valore di ritorno

- -

Un nuovo array con ciascun elemento che è il risultato della funzione di callback.

- -

Descrizione

- -

map chiama il callback fornito una volta per ciascun elemento in un array, in ordine, e costruisce un nuovo array dai risultati. callback viene invocato solo per gli indici dell'array che hanno valori assegnati, incluso undefined. 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).

- -

Poichè map costruisce un nuovo array, usarlo quando non si utilizza l'array restituito è un anti-pattern; usa forEachfor-of invece. Segni che non dovresti usare map: A) Non stai usando l'array restituito, e/o B) Non stai restituendo un valore dal callback.

- -

callback viene invocato con tre argomenti: il valore dell'elemento, l'indice dell'elemento e l'oggetto Array che viene iterato.

- -

Se viene fornito il parametro thisArg a map, verrà utilizzato come valore this del callback. Altrimenti, il valore {{jsxref("undefined")}} sarà usato come valore this. Il valore this alla fine osservabile da callback è determinato secondo le consuete regole per determinare il this visto da una funzione.

- -

map non muta l'array su cui è chiamato (sebbene callback, se invocato, possa farlo).

- -

L'intervallo di elementi elaborati da map viene impostato prima della prima chiamata del callback. Gli elementi aggiunti all'array dopo che la chiamata a map inizia non saranno calcolati da callback. Se i valori degli elementi esistenti dell'array vengono modificati, il valore passato a callback sarà il valore al momento in cui map li visita. Gli elementi che vengono cancellati dopo che la chiamata a map inizia e prima di essere visitati non vengono visitati.

- -

A causa dell'algoritmo definito nella specifica, se l'array su cui è stata chiamato map è sparso, l'array risultante sarà sparso, mantenendo vuoti gli stessi indici.

- -

Esempi

- -

Mappare una serie di numeri ad un array di radici quadrate

- -

Il seguente codice accetta un array di numeri e crea un nuovo array contenente le radici quadrate dei numeri nel primo array.

- -
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]
-
- -

Usare map per riformattare gli oggetti in un array

- -

Il seguente codice accetta un array di oggetti e crea un nuovo array contenente gli oggetti appena riformattati.

- -
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}]
-
- -

Mappare un array di numeri usando una funzione che contiene un argomento

- -

Il codice seguente mostra come funziona map quando viene utilizzata una funzione che richiede un argomento. L'argomento verrà assegnato automaticamente da ciascun elemento dell'array mentre map itera l'array originale.

- -
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]
-
- -

Usare map genericamente

- -

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:

- -
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]
-
- -

Usare map con querySelectorAll

- -

Questo esempio mostra come iterare attraverso una raccolta di oggetti raccolti da querySelectorAll. Questo perchè querySelectorAll restituisce una NodeList che è una raccolta di oggetti.
- In questo caso restituiamo sullo schermo tutti i valori delle opzioni selezionate:

- -
var elems = document.querySelectorAll('select option:checked');
-var values = Array.prototype.map.call(elems, function(obj) {
-  return obj.value;
-});
-
- -

Il modo più semplice sarebbe utilizzare il metodo {{jsxref("Array.from()")}}.

- -

Caso d'uso ingannevole

- -

(inspired by this blog post)

- -

È 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.

- -
// 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]
-
- -

Un output alternativo del metodo map che viene chiamato con parseInt come parametro viene eseguito come segue:

- -
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.
- -

Polyfill

- -

map è 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 map 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 callback.call restituisce il valore originale di {{jsxref("Function.prototype.call")}}.

- -
// 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;
-  };
-}
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ESDraft')}} 
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.map")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/of/index.html b/files/it/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 808c1dda2c..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -

Il metodo Array.of() crea una nuova istanza di Array  accettando un numero variabile di argomenti, indipendentemente dal numero o dal tipo degli argomenti.

- -

La differenza tra Array.of() ed il costruttore Array è nella gestione degli argomenti di tipo intero: Array.of(7) crea un array con un singolo elemento, 7, mentre Array(7) crea un array vuoto con la proprietà length settata a  7 (Nota: questo implica un array di 7 elementi vuoti, non elementi col valore undefined assegnato).

- -
Array.of(7);       // [7]
-Array.of(1, 2, 3); // [1, 2, 3]
-
-Array(7);          // [ , , , , , , ]
-Array(1, 2, 3);    // [1, 2, 3]
-
- -

Syntax

- -
Array.of(element0[, element1[, ...[, elementN]]])
- -

Parameteri

- -
-
elementN
-
Gli elementi da assegnare all'array.
-
- -

Valore di ritorno

- -

Una nuova istanz di {{jsxref("Array")}}.

- -

Descrizione

- -

Questa funzione fa parte dello standard ECMAScript 2015. Per maggiori informazioni vedi le proposal Array.of e Array.from  e il polyfill Array.of.

- -

Esempi

- -
Array.of(1);         // [1]
-Array.of(1, 2, 3);   // [1, 2, 3]
-Array.of(undefined); // [undefined]
-
- -

Polyfill

- -

Eseguendo il codice seguente prima di qualsiasi altro codice verrà creato il metodo Array.of() se non era precedentemente esistente.

- -
if (!Array.of) {
-  Array.of = function() {
-    return Array.prototype.slice.call(arguments);
-  };
-}
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.of")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/pop/index.html b/files/it/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index 6feabb5f14..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - Array - - JavaScript - - Prototype - - Referenza - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

Il metodo pop() rimuove l'ultimo elemento da un array e restituisce quell'elemento. Questo metodo modifica la lunghezza dell'array.

- -
{{EmbedInteractiveExample("pages/js/array-pop.html")}}
- - - -

Sintassi

- -
arr.pop()
- -

Valore di ritorno

- -

L'elemento rimosso dall'array; {{jsxref("undefined")}} se l'array è vuoto.

- -

Descrizione

- -

Il metodo pop rimuove l'ultimo elemento da un array e restituisce quel valore al chiamante.

- -

pop è intenzionalmente generico; questo metodo può essere {{jsxref("Function.call", "chiamato", "", 1)}} o {{jsxref("Function.apply", "applicato", "", 1)}} ad oggetti che assomigliano agli array. Gli oggetti che non contengono una proprietà length che riflette l'ultimo di una serie di proprietà numeriche consecutive basate su zero potrebbero non comportarsi in alcun modo significativo.

- -

Se chiami pop() su un array vuoto, ritorna {{jsxref("undefined")}}.

- -

{{jsxref("Array.prototype.shift()")}} ha un comportamento simile a pop, ma applicato al primo elemento di un array.

- -

Esempi

- -

Rimozione dell'ultimo elemento di un array

- -

Il seguente codice crea l'array myFish contenente quattro elementi, dopo rimuove il suo ultimo elemento.

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-
-var popped = myFish.pop();
-
-console.log(myFish); // ['angel', 'clown', 'mandarin' ]
-
-console.log(popped); // 'sturgeon'
- - - -

Usare apply( ) o call ( ) sugli array-like objects

- -

Il codice seguente crea l'array-like object myFish contenente quattro elementi e un parametro length, poi rimuove il suo ultimo elemento e decrementa il parametro length.

- -
var myFish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4};
-
-var popped = Array.prototype.pop.call(myFish); //same syntax for using apply( )
-
-console.log(myFish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3}
-
-console.log(popped); // 'sturgeon'
-
- - - -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale Implementato in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}}
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.pop")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/push/index.html b/files/it/web/javascript/reference/global_objects/array/push/index.html deleted file mode 100644 index ad34c3da2d..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/push/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Array.prototype.push() -slug: Web/JavaScript/Reference/Global_Objects/Array/push -translation_of: Web/JavaScript/Reference/Global_Objects/Array/push ---- -
{{JSRef}}
- -

Il metodo push() aggiunge uno o più elementi alla fine di un array e ne restituisce la nuova lunghezza.

- -
var numbers = [1, 2, 3];
-numbers.push(4);
-
-console.log(numbers); // [1, 2, 3, 4]
-
-numbers.push(5, 6, 7);
-
-console.log(numbers); // [1, 2, 3, 4, 5, 6, 7]
-
- -

Sintassi

- -
arr.push([elemento1[, ...[, elementoN]]])
- -

Parametri

- -
-
elementoN
-
Gli elementi da aggiungere alla fine dell'array.
-
- -

Valore di ritorno

- -

La nuova proprietà {{jsxref("Array.length", "length")}} dell'oggetto su cui è stato richiamato il metodo.

- -

Descrizione

- -

Il metodo push aggiunge valori all'array.

- -

push è intenzionalmente generico. Questo metodo può essere utilizzato con {{jsxref("Function.call", "call()")}} o {{jsxref("Function.apply", "apply()")}} su oggetti che assomigliano a un array. Il metodopush si basa sulla proprietà length per determinare da dove iniziare l'inserimento dei valori indicati. Se la proprietà length non può essere convertita in un numero, l'indice utilizzato è 0. Ciò include la possibilità che length sia inesistente, in tale caso length verrà creata.

- -

Gli unici oggetti nativi simili agli array sono {{jsxref("Global_Objects/String", "strings", "", 1)}}, anche se non adatti alle applicazioni di questo metodo, in quanto le stringhe sono immutabili.

- -

Esempi

- -

Aggiungere elementi a un array

- -

Il seguente codice crea l'array sports che contiene due elementi, poi aggiunge ulteriori due elementi allo stesso. La variabile total contiene la nuova lunghezza dell'array.

- -
var sports = ['calcio', 'baseball'];
-var total = sports.push('football americano', 'nuoto');
-
-console.log(sports); // ['calcio', 'baseball', 'football americano', 'nuoto']
-console.log(total); // 4
-
- -

Unire due arrays

- -

Questo esempio utilizza {{jsxref("Function.apply", "apply()")}} per aggiungere tutti gli elementi da un secondo array.

- -

Non utilizzare questo metodo se il secondo array (moreVegs in questo esempio) è molto grande, perché il numero massimo di parametri che una funzione può assumere è limitato nella pratica. Vedere {{jsxref("Function.apply", "apply()")}} per ulteriori dettagli.

- -
var vegetables = ['pastinaca', 'patata'];
-var moreVegs = ['sedano', 'barbabietola'];
-
-// Unire il secondo array nel primo
-// Equivalente a vegetables.push('sedano', 'barbabietola');
-Array.prototype.push.apply(vegetables, moreVegs);
-
-console.log(vegetables); // ['pastinaca', 'patata', 'sedano', 'barbabietola']
-
- -

Utilizzo di un oggetto come un array

- -

Come accennato in precedenza, push è intenzionalmente generica e possiamo usarla a nostro vantaggio. Array.prototype.push può funzionare benissimo su un oggetto, come mostra questo esempio. Si noti che non creiamo un array per memorizzare la raccolta di oggetti. Al contrario, memorizziamo la raccolta sull'oggetto stesso e utilizziamo call su Array.prototype.push per ingannare il metodo e fargli pensare che siamo di fronte a un array, e funziona solo grazie al modo in cui JavaScript ci permette di stabilire il contesto di esecuzione come preferiamo.

- -
var obj = {
-    length: 0,
-
-    addElem: function addElem(elem) {
-        // obj.length viene automaticamente incrementato
-        // ogni volta che viene aggiunto un elemento.
-        [].push.call(this, elem);
-    }
-};
-
-// Aggiungiamo alcuni oggetti vuoti solo per illustrare.
-obj.addElem({});
-obj.addElem({});
-console.log(obj.length);
-// → 2
-
- -

Si noti che anche se obj non è un array, il metodo push ha incrementato la proprietà di length diobj come se si trattasse di un array vero e proprio.

- -

Specificazioni

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificazioneStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale. Implementato in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ESDraft')}}
- -

Compatibilità di Browser

- -
- - -

{{Compat("javascript.builtins.Array.push")}}

-
- -

Guarda anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/reduce/index.html b/files/it/web/javascript/reference/global_objects/array/reduce/index.html deleted file mode 100644 index de063df929..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/reduce/index.html +++ /dev/null @@ -1,576 +0,0 @@ ---- -title: Array.prototype.reduce() -slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce -tags: - - Array - - Array method - - ECMAScript 5 - - JavaScript - - Method - - Prototype - - Reduce - - Referenza -translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce ---- -
{{JSRef}}
- -

Il metodo reduce() esegue una funzione reducer (che tu fornisci) su ogni elemento dell'array, risultante in un unico output.

- -
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
- -
I sorgenti per questo esempio interattivo è disponibile su un repository GitHub. Se desideri contribuire al progetto, clona https://github.com/mdn/interactive-examples e inviaci una pull request.
- -

La funzione reducer accetta quattro argomenti:

- -
    -
  1. Accumulatore (acc)
  2. -
  3. Valore corrente (cur)
  4. -
  5. Indice corrente (idx)
  6. -
  7. Array sul quale viene eseguito il metodo (src)
  8. -
- -

Il valore restituito della funzione reducer viene assegnato all'accumulatore, il cui valore viene memorizzato attraverso ogni iterazione nell'intero array e in definitiva, diventa il valore finale finale singolo.

- -

Sintassi

- -
arr.reduce(callback(accumulator, currentValue[, index[, array]]) [, initialValue])
- -

Parametri

- -
-
callback
-
Una funzione da eseguire su ogni elemento dell'array (tranne il primo, se non viene fornita initialValue), accetta 4 argomenti: -
-
accumulator
-
L'accumulatore accumula i valori di ritorno del callback. È il valore accumulato precedentemente restituito nell'ultima chiamata del callback o initialValue, se fornito (vedere di seguito).
-
currentValue
-
L'elemento corrente in elaborazione nell'array.
-
index {{optional_inline}}
-
L'indice dell'elemento corrente in elaborazione nell'array. Inizia dall'indice 0 se viene fornito initialValue Altrimenti, inizia dall'indice 1.
-
array {{optional_inline}}
-
L'array a cui viene applicato reduce().
-
-
-
initialValue {{optional_inline}}
-
Un valore da utilizzare come primo argomento della prima chiamata del callback. Se non viene fornito initialValue il primo elemento dell'array verrà utilizzato e saltato. Chiamare reduce() su un array vuoto senza initialValue genererà un TypeError.
-
- -

Valore di ritorno

- -

Il singolo valore che risulta dalla riduzione.

- -

Descrizione

- -

Il metodo reduce() esegue il callback una volta per ogni valore assegnato presente nell'array, prendendo quattro argomenti:

- - - -

La prima volta che viene chiamato il callback, accumulator e currentValue possono essere uno dei due valori. Se initialValue viene fornito nella chiamata a reduce(), accumulator sarà uguale a initialValue, e currentValue sarà uguale al primo valore nell'array. Se non viene fornito alcun valore initialValue, accumulator sarà uguale al primo valore dell'array e currentValue sarà uguale al secondo.

- -
-

Note: Se non viene fornito initialValue, reduce() eseguirà la funzione di callback a partire dall'indice 1, saltando il primo indice. Se viene fornito initialValue, inizierà dall'indice 0.

-
- -

Se l'array è vuoto e non viene fornito initialValue verrà generato un {{jsxref("TypeError")}}. Se l'array ha solo un elemento (indipendentemente dalla posizione) e non viene fornito initialValue, o se è fornito initialValue ma l'array è vuoto, il valore solo verrà restituito senza chiamare callback.

- -

Di solito è più sicuro fornire initialValue perché ci sono tre output possibili senza initialValue, come mostrato nell'esempio seguente.

- -
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
-var maxCallback2 = ( max, cur ) => Math.max( max, cur );
-
-// reduce() without initialValue
-[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
-[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
-[                      ].reduce( maxCallback ); // TypeError
-
-// map/reduce; better solution, also works for empty or larger arrays
-[ { x: 22 }, { x: 42 } ].map( el => el.x )
-                        .reduce( maxCallback2, -Infinity );
-
- -

Come funziona reduce()

- -

Supponiamo che si sia verificato il seguente uso di reduce():

- -
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
-  return accumulator + currentValue;
-});
-
- -

Il callback verrebbe invocato quattro volte, con gli argomenti e i valori restituiti in ogni chiamata come segue:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarrayvalore ritornato
prima chiamata011[0, 1, 2, 3, 4]1
seconda chiamata122[0, 1, 2, 3, 4]3
terza chiamata333[0, 1, 2, 3, 4]6
quarta chiamata644[0, 1, 2, 3, 4]10
- -

Il valore restituito da reduce() sarà quello dell'ultima chiamata del callback (10).

- -

È inoltre possibile fornire una {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} al posto di una funzione completa. Il seguente codice produrrà lo stesso output del codice nel blocco sopra riportato:

- -
[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
-
- -

Se dovessi fornire initialValue come secondo argomento a reduce(), il risultato sarebbe simile a questo:

- -
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
-    return accumulator + currentValue;
-}, 10);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarrayvalore restituito
prima chiamata1000[0, 1, 2, 3, 4]10
seconda chiamata1011[0, 1, 2, 3, 4]11
terza chiamata1122[0, 1, 2, 3, 4]13
quarta chiamata1333[0, 1, 2, 3, 4]16
quinta chiamata1644[0, 1, 2, 3, 4]20
- -

Il valore restituito da reduce() in questo caso sarebbe 20.

- -

Esempi

- -

Sommare tutti i valori di un array

- -
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
-  return accumulator + currentValue;
-}, 0);
-// sum è 6
-
-
- -

In alternativa scritto con una arrow function:

- -
var total = [ 0, 1, 2, 3 ].reduce(
-  ( accumulator, currentValue ) => accumulator + currentValue,
-  0
-);
- -

Somma dei valori in un array di oggetti

- -

Per riassumere i valori contenuti in un array di oggetti, devi fornire initialValue, in modo che ogni elemento passi attraverso la tua funzione

- -
var initialValue = 0;
-var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
-    return accumulator + currentValue.x;
-},initialValue)
-
-console.log(sum) // logs 6
-
- -

In alternativa scritto con una arrow function:

- -
var initialValue = 0;
-var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
-    (accumulator, currentValue) => accumulator + currentValue.x
-    ,initialValue
-);
-
-console.log(sum) // logs 6
- -

Appiattire una serie di array

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  function(accumulator, currentValue) {
-    return accumulator.concat(currentValue);
-  },
-  []
-);
-// flattened is [0, 1, 2, 3, 4, 5]
-
- -

In alternativa scritto con una arrow function:

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  ( accumulator, currentValue ) => accumulator.concat(currentValue),
-  []
-);
-
- -

Conteggio delle istanze di valori in un oggetto

- -
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
-
-var countedNames = names.reduce(function (allNames, name) {
-  if (name in allNames) {
-    allNames[name]++;
-  }
-  else {
-    allNames[name] = 1;
-  }
-  return allNames;
-}, {});
-// countedNames is:
-// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
-
- -

Raggruppamento di oggetti in base a una proprietà

- -
var people = [
-  { name: 'Alice', age: 21 },
-  { name: 'Max', age: 20 },
-  { name: 'Jane', age: 20 }
-];
-
-function groupBy(objectArray, property) {
-  return objectArray.reduce(function (acc, obj) {
-    var key = obj[property];
-    if (!acc[key]) {
-      acc[key] = [];
-    }
-    acc[key].push(obj);
-    return acc;
-  }, {});
-}
-
-var groupedPeople = groupBy(people, 'age');
-// groupedPeople is:
-// {
-//   20: [
-//     { name: 'Max', age: 20 },
-//     { name: 'Jane', age: 20 }
-//   ],
-//   21: [{ name: 'Alice', age: 21 }]
-// }
-
- -

Array di legame contenuti in una serie di oggetti che utilizzano lo spread operator e initialValue

- -
// friends - an array of objects
-// where object field "books" - list of favorite books
-var friends = [{
-  name: 'Anna',
-  books: ['Bible', 'Harry Potter'],
-  age: 21
-}, {
-  name: 'Bob',
-  books: ['War and peace', 'Romeo and Juliet'],
-  age: 26
-}, {
-  name: 'Alice',
-  books: ['The Lord of the Rings', 'The Shining'],
-  age: 18
-}];
-
-// allbooks - list which will contain all friends' books +
-// additional list contained in initialValue
-var allbooks = friends.reduce(function(accumulator, currentValue) {
-  return [...accumulator, ...currentValue.books];
-}, ['Alphabet']);
-
-// allbooks = [
-//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
-//   'Romeo and Juliet', 'The Lord of the Rings',
-//   'The Shining'
-// ]
- -

Rimuovi gli elementi duplicati nell'array

- -
-

Note: Se si utilizza un ambiente compatibile con {{jsxref("Set")}} e {{jsxref("Array.from()")}}, è possibile utilizzare let orderedArray = Array.from(new Set(myArray)); per ottenere un array in cui sono stati rimossi gli elementi duplicati.

-
- -
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
-var myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
-  if (accumulator.indexOf(currentValue) === -1) {
-    accumulator.push(currentValue);
-  }
-  return accumulator
-}, [])
-
-console.log(myOrderedArray);
- -

Eseguire le Promises in Sequenza

- -
/**
- * Esegue promises da un array di funzioni che possono restituire promises
- * in modo concatenato
- *
- * @param {array} arr - promise arr
- * @return {Object} promise object
- */
-function runPromiseInSequence(arr, input) {
-  return arr.reduce(
-    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
-    Promise.resolve(input)
-  );
-}
-
-// promise function 1
-function p1(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 5);
-  });
-}
-
-// promise function 2
-function p2(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 2);
-  });
-}
-
-// function 3  - sarà avvolta in una promise risolta da .then()
-function f3(a) {
- return a * 3;
-}
-
-// promise function 4
-function p4(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 4);
-  });
-}
-
-const promiseArr = [p1, p2, f3, p4];
-runPromiseInSequence(promiseArr, 10)
-  .then(console.log);   // 1200
-
- -

Composizione funzionale per tubazioni

- -
// Elementi da utilizzare per la composizione
-const double = x => x + x;
-const triple = x => 3 * x;
-const quadruple = x => 4 * x;
-
-// Function composition enabling pipe functionality
-const pipe = (...functions) => input => functions.reduce(
-    (acc, fn) => fn(acc),
-    input
-);
-
-// Funzioni composte per la moltiplicazione di valori specifici
-const multiply6 = pipe(double, triple);
-const multiply9 = pipe(triple, triple);
-const multiply16 = pipe(quadruple, quadruple);
-const multiply24 = pipe(double, triple, quadruple);
-
-// Utilizzo
-multiply6(6); // 36
-multiply9(9); // 81
-multiply16(16); // 256
-multiply24(10); // 240
-
-
- -

Scrivere map usando reduce

- -
if (!Array.prototype.mapUsingReduce) {
-  Array.prototype.mapUsingReduce = function(callback, thisArg) {
-    return this.reduce(function(mappedArray, currentValue, index, array) {
-      mappedArray[index] = callback.call(thisArg, currentValue, index, array);
-      return mappedArray;
-    }, []);
-  };
-}
-
-[1, 2, , 3].mapUsingReduce(
-  (currentValue, index, array) => currentValue + index + array.length
-); // [5, 7, , 10]
-
-
- -

Polyfill

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.21
-// Reference: http://es5.github.io/#x15.4.4.21
-// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
-if (!Array.prototype.reduce) {
-  Object.defineProperty(Array.prototype, 'reduce', {
-    value: function(callback /*, initialValue*/) {
-      if (this === null) {
-        throw new TypeError( 'Array.prototype.reduce ' +
-          'called on null or undefined' );
-      }
-      if (typeof callback !== 'function') {
-        throw new TypeError( callback +
-          ' is not a function');
-      }
-
-      // 1. Let O be ? ToObject(this value).
-      var o = Object(this);
-
-      // 2. Let len be ? ToLength(? Get(O, "length")).
-      var len = o.length >>> 0;
-
-      // Steps 3, 4, 5, 6, 7
-      var k = 0;
-      var value;
-
-      if (arguments.length >= 2) {
-        value = arguments[1];
-      } else {
-        while (k < len && !(k in o)) {
-          k++;
-        }
-
-        // 3. If len is 0 and initialValue is not present,
-        //    throw a TypeError exception.
-        if (k >= len) {
-          throw new TypeError( 'Reduce of empty array ' +
-            'with no initial value' );
-        }
-        value = o[k++];
-      }
-
-      // 8. Repeat, while k < len
-      while (k < len) {
-        // a. Let Pk be ! ToString(k).
-        // b. Let kPresent be ? HasProperty(O, Pk).
-        // c. If kPresent is true, then
-        //    i.  Let kValue be ? Get(O, Pk).
-        //    ii. Let accumulator be ? Call(
-        //          callbackfn, undefined,
-        //          « accumulator, kValue, k, O »).
-        if (k in o) {
-          value = callback(value, o[k], k, o);
-        }
-
-        // d. Increase k by 1.
-        k++;
-      }
-
-      // 9. Return accumulator.
-      return value;
-    }
-  });
-}
-
- -

Se hai bisogno di supportare motori JavaScript veramente obsoleti che non supportano Object.defineProperty(), è meglio non applicare polyfills ai metodi di Array.prototype, poiché non puoi renderli non enumerabili.

- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}}
- -

Compatibilità con i browser

- -

La tabella di compatibilità in questa pagina è generata a partire da dati strutturati. Se desideri contribuire ai dati, visita https://github.com/mdn/browser-compat-data e inviaci una pull request.

- -
-

{{Compat("javascript.builtins.Array.reduce")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/reverse/index.html b/files/it/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index 750befde61..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

Il metodo reverse()  inverte ua matrice (array) sul posto. Il primo elemento di matrice diventa l'ultima, e l'ultimo elemento di matrice diventa il primo.

- -
var a = ['one', 'two', 'three'];
-a.reverse();
-
-console.log(a); // ['three', 'two', 'one']
-
- -

Sintassi

- -
a.reverse()
- -

Valore prodotto. 

- -

La matrice invertita.

- -

Descrizione

- -

Il metodo reverse traspone gli elementi della matrice chiamata, mutando la matrice, e restituendo un riferimento alla matrice.

- -

Esempi

- -

Inversione degli elementi nella matrice

- -

L'esempio seguente crea una matrice a, contenente tre elementi, quindi inverte la matrice. La chiamata ad invertire () restituisce un riferimento alla matrice invertita a.

- -
var a = ['one', 'two', 'three'];
-var reversed = a.reverse();
-
-console.log(a);        // ['three', 'two', 'one']
-console.log(reversed); // ['three', 'two', 'one']
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}definizione iniziale. Implementata in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}}
- -

Compatibilità browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
CaratteristicaChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Supporto base{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatVersionUnknown}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/slice/index.html b/files/it/web/javascript/reference/global_objects/array/slice/index.html deleted file mode 100644 index 419da77ae4..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/slice/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Array.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/Array/slice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice ---- -
{{JSRef}}
- -

Il metodo slice() ritorna la copia di una porzione dell'array contenente gli elementi compresi tra inzio e fine (fine escluso). Il metodo slice() ritorna la copia dell'intero array se non  contiene gli elementi di inizio e fine. L'array di partenza non viene modificato.

- -
var a = ['zero', 'one', 'two', 'three'];
-var sliced = a.slice(1, 3);
-
-console.log(a);      // ['zero', 'one', 'two', 'three']
-console.log(sliced); // ['one', 'two']
-
- -

Sintassi

- -
arr.slice()
-arr.slice(inizio)
-arr.slice(inizio, fine)
-
- -

Parametri

- -
-
begin {{optional_inline}}
-
L'indice zero-based indica da dove inizia l'intervallo da selezionare.
-
Può essere utilizzato un indice negativo, indicante l'offset dall'ultimo elemento dell'array. slice(-2) seleziona gli ultimi due elementi della sequenza.
-
Se begin non viene impostato , slice parte dall'indice 0.
-
end {{optional_inline}}
-
L' indice zero-base indica dove finisce l'intervallo da selezionare. slice seleziona gli elementi fino a quell'indice ma non l'elemento all'indice end.
-
Per esempio, slice(1,4)estrae dal secondo elemento dell'array al quarto escluso (elementi con indice 1, 2 e 3).
-
Puo essere utilizzato un indice negativo, tale indice indicherebbe l'offset dall'ultimo elemento dell'array. slice(2,-1) estrae dal terzo elemento della sequenza al penuntimo.
-
Se end non viene impostato, slice continua l'estrazione sino al termine dell'array (arr.length).
-
Se end è maggiore della lunghezza della sequenza , slice continua l'estrazione sino al termine dell'array (arr.length).
-
- -

Return value

- -

Un nuovo array che contiene gli elementi estratti.

- -

Descrizione

- -

slice non modifica l'array originale. Restituisce una copia superficiale degli elementi dell'array originale. Gli elementi dell'array originale vengono copiati nell'array restituito come segue:

- - - -

Se viene aggiunto un nuovo elemento in uno degli array, l'altro non viene modificato.

- -

Esempi

- -

Restituire una porzione dell'array esistente

- -
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
-var citrus = fruits.slice(1, 3);
-
-// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-// citrus contains ['Orange','Lemon']
-
- -

Utilizzare slice

- -

Nell'esempio che segue, slice crea un nuovo array, newCar, da myCar. Entrambi includono un riferimento all'oggetto myHonda. Quando il colore di myHonda diventa viola, entrambi gli array riflettono la modifica.

- -
// Creare newCar da myCar utilizzando slice.
-var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
-var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'];
-var newCar = myCar.slice(0, 2);
-
-// Mostrare i valori di myCar, newCar, e il colore di myHonda
-//  riferiti da entrambi gli array.
-console.log('myCar = ' + JSON.stringify(myCar));
-console.log('newCar = ' + JSON.stringify(newCar));
-console.log('myCar[0].color = ' + myCar[0].color);
-console.log('newCar[0].color = ' + newCar[0].color);
-
-// Modificare il colore di myHonda.
-myHonda.color = 'purple';
-console.log('The new color of my Honda is ' + myHonda.color);
-
-// Mostrare il colore di myHonda riferito da entrambi gli array.
-console.log('myCar[0].color = ' + myCar[0].color);
-console.log('newCar[0].color = ' + newCar[0].color);
-
- -

Lo script scrive:

- -
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
-         'cherry condition', 'purchased 1997']
-newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
-myCar[0].color = red
-newCar[0].color = red
-The new color of my Honda is purple
-myCar[0].color = purple
-newCar[0].color = purple
-
- -

Oggetti Array-like

- -

Il metodo slice può essere chiamato anche per convertire gli oggetti o le collezioni Array-like in un nuovo Array. Basta legare il metodo all'oggetto. {{jsxref("Functions/arguments", "arguments")}} all'interno di una funzione è un esempio di 'array-like object'.

- -
function list() {
-  return Array.prototype.slice.call(arguments);
-}
-
-var list1 = list(1, 2, 3); // [1, 2, 3]
-
- -

Il binding può essere effettuato con la funzione .call di {{jsxref("Function.prototype")}} e può anche essere ridotto utilizzando [].slice.call(arguments) invece di Array.prototype.slice.call. Ad ogni modo, può essere semplificato utilizzando {{jsxref("Function.prototype.bind", "bind")}}.

- -
var unboundSlice = Array.prototype.slice;
-var slice = Function.prototype.call.bind(unboundSlice);
-
-function list() {
-  return slice(arguments);
-}
-
-var list1 = list(1, 2, 3); // [1, 2, 3]
-
- -

Streamlining cross-browser behavior

- -

Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by Array.prototype.slice and IE < 9 does not do so, versions of IE starting with version 9 do allow this. “Shimming” it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently de facto standard behavior. (The shim also fixes IE to work with the second argument of slice() being an explicit {{jsxref("null")}}/{{jsxref("undefined")}} value as earlier versions of IE also did not allow but all modern browsers, including IE >= 9, now do.)

- -
/**
- * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
- * on host objects like NamedNodeMap, NodeList, and HTMLCollection
- * (technically, since host objects have been implementation-dependent,
- * at least before ES2015, IE hasn't needed to work this way).
- * Also works on strings, fixes IE < 9 to allow an explicit undefined
- * for the 2nd argument (as in Firefox), and prevents errors when
- * called on other DOM objects.
- */
-(function () {
-  'use strict';
-  var _slice = Array.prototype.slice;
-
-  try {
-    // Can't be used with DOM elements in IE < 9
-    _slice.call(document.documentElement);
-  } catch (e) { // Fails in IE < 9
-    // This will work for genuine arrays, array-like objects,
-    // NamedNodeMap (attributes, entities, notations),
-    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
-    // and will not fail on other DOM objects (as do DOM elements in IE < 9)
-    Array.prototype.slice = function(begin, end) {
-      // IE < 9 gets unhappy with an undefined end argument
-      end = (typeof end !== 'undefined') ? end : this.length;
-
-      // For native Array objects, we use the native slice function
-      if (Object.prototype.toString.call(this) === '[object Array]'){
-        return _slice.call(this, begin, end);
-      }
-
-      // For array like object we handle it ourselves.
-      var i, cloned = [],
-        size, len = this.length;
-
-      // Handle negative value for "begin"
-      var start = begin || 0;
-      start = (start >= 0) ? start : Math.max(0, len + start);
-
-      // Handle negative value for "end"
-      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
-      if (end < 0) {
-        upTo = len + end;
-      }
-
-      // Actual expected size of the slice
-      size = upTo - start;
-
-      if (size > 0) {
-        cloned = new Array(size);
-        if (this.charAt) {
-          for (i = 0; i < size; i++) {
-            cloned[i] = this.charAt(start + i);
-          }
-        } else {
-          for (i = 0; i < size; i++) {
-            cloned[i] = this[start + i];
-          }
-        }
-      }
-
-      return cloned;
-    };
-  }
-}());
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.slice")}}

-
- -

See also

- - diff --git a/files/it/web/javascript/reference/global_objects/array/some/index.html b/files/it/web/javascript/reference/global_objects/array/some/index.html deleted file mode 100644 index 3befa8a8b0..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/some/index.html +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Array.prototype.some() -slug: Web/JavaScript/Reference/Global_Objects/Array/some -translation_of: Web/JavaScript/Reference/Global_Objects/Array/some ---- -
{{JSRef}}
- -

Il metodo some() verifica se almeno un elemento nell'array passa la verifica implementata dalla funzione fornita.

- -
-

Note: Questo metodo ritorna false per qualsiasi condizione passata ad un array vuoto.

-
- - - -
{{EmbedInteractiveExample("pages/js/array-some.html")}}
- - - -

Sintassi

- -
arr.some(callback[, thisArg])
- -

Parametri

- -
-
callback
-
Funzione di test per ogni elemento, prende tre elementi: -
-
valoreCorrente
-
Il valore corrente dell'elemento che deve essere processato nell'array.
-
indice {{Optional_inline}}
-
l'indice dell'elemento corrente dell'array.
-
array{{Optional_inline}}
-
l'array completo alla quale è stato chiamato il some().
-
-
-
thisArg{{Optional_inline}}
-
Valore da usare come this quando si esegue la callback.
-
- -

Valore ritornato

- -

true se la funzione di callback ha ritornato un valore {{Glossary("truthy")}} per almeno un elemento nell'array; altrimenti, false.

- -

Descrizione

- -

some() esegue la funzione di callback per ogni elemento presente nell'array finchè non ne trova uno dove la callback retorna un valore truthy (un valore che ritorna true se convertito in un Booleano). Se viene trovato un elemento di questo genere allora some() ritorna immediatamente true. altrimenti, some() ritorna false. callback viene invocato solamente solamente per gli elementi che hanno un valore assegnato; quindi non viene chiamato per elementi eliminati o mai assegnati.

- -

callback è invocato con tre argomenti: il valore dell'elemento, l'indice dell'elemento nell'array, e l'array dalla quale è stato invocato.

- -

se viene passato un parametro thisArg al metodo some(), verrà usato come valore this per le callbacks. altrimenti, verrà usato il valore {{jsxref("undefined")}} come valore di this. Il valore di this nella callback è determinato in accordo con le normali regole per determinare il valore di this nelle funzioni.

- -

some() non muta l'array dalla quale è stato evocato.

- -

Il range di elementi processati da some() è impostato prima della prima chiamata alla callback. Gli elementi che vengono attaccati o aggiunti all'array dopo che è stata effettuata la chiamata al metodo some() non verranno tenuti in considerazione. Se al contrario un elemento viene cambiato prima che venga processato dalla callback, il valore passato sarà quello modificato.  Elementi eliminati invece non verranno controllati. 

- -

Esempi

- -

Testare i valori all'interno di un array

- -

L'esempio seguente testa se almeno un elemento dell'array è maggiore di 10.

- -
function isBiggerThan10(element, index, array) {
-  return element > 10;
-}
-
-[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
-[12, 5, 8, 1, 4].some(isBiggerThan10); // true
-
- -

Testing array elements using arrow functions

- -

Arrow functions provide a shorter syntax for the same test.

- -
[2, 5, 8, 1, 4].some(x => x > 10);  // false
-[12, 5, 8, 1, 4].some(x => x > 10); // true
-
- -

Checking whether a value exists in an array

- -

To mimic the function of the includes() method, this custom function returns true if the element exists in the array:

- -
var fruits = ['apple', 'banana', 'mango', 'guava'];
-
-function checkAvailability(arr, val) {
-  return arr.some(function(arrVal) {
-    return val === arrVal;
-  });
-}
-
-checkAvailability(fruits, 'kela');   // false
-checkAvailability(fruits, 'banana'); // true
- -

Checking whether a value exists using an arrow function

- -
var fruits = ['apple', 'banana', 'mango', 'guava'];
-
-function checkAvailability(arr, val) {
-  return arr.some(arrVal => val === arrVal);
-}
-
-checkAvailability(fruits, 'kela');   // false
-checkAvailability(fruits, 'banana'); // true
- -

Converting any value to Boolean

- -
var TRUTHY_VALUES = [true, 'true', 1];
-
-function getBoolean(value) {
-  'use strict';
-
-  if (typeof value === 'string') {
-    value = value.toLowerCase().trim();
-  }
-
-  return TRUTHY_VALUES.some(function(t) {
-    return t === value;
-  });
-}
-
-getBoolean(false);   // false
-getBoolean('false'); // false
-getBoolean(1);       // true
-getBoolean('true');  // true
- -

Polyfill

- -

some() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that fun.call evaluates to the original value of {{jsxref("Function.prototype.call()")}}.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.17
-// Reference: http://es5.github.io/#x15.4.4.17
-if (!Array.prototype.some) {
-  Array.prototype.some = function(fun/*, thisArg*/) {
-    'use strict';
-
-    if (this == null) {
-      throw new TypeError('Array.prototype.some called on null or undefined');
-    }
-
-    if (typeof fun !== 'function') {
-      throw new TypeError();
-    }
-
-    var t = Object(this);
-    var len = t.length >>> 0;
-
-    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
-    for (var i = 0; i < len; i++) {
-      if (i in t && fun.call(thisArg, t[i], i, t)) {
-        return true;
-      }
-    }
-
-    return false;
-  };
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.some")}}

-
- -

See also

- - diff --git a/files/it/web/javascript/reference/global_objects/array/sort/index.html b/files/it/web/javascript/reference/global_objects/array/sort/index.html deleted file mode 100644 index 6c16c7dd6b..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/sort/index.html +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: Array.prototype.sort() -slug: Web/JavaScript/Reference/Global_Objects/Array/sort -tags: - - Array - - JavaScript - - Metodi - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort ---- -
{{JSRef}}
- -

Il metodo sort() ordina gli elementi di un array in place e ritorna l'array. L'ordinamento non è necessariamente stable. L'ordinamento predefinito è in base ai punti di codice Unicode della stringa.

- -

Il tempo e la complessità dell'ordinamento dipendono dall'implementazione, perciò non possono essere garantiti.

- -
var fruit = ['cherries', 'apples', 'bananas'];
-fruit.sort(); // ['apples', 'bananas', 'cherries']
-
-var scores = [1, 10, 21, 2];
-scores.sort(); // [1, 10, 2, 21]
-// Nota che 10 viene prima di 2,
-// perché '10' è l'insieme di due caratteri '1' e '0' così '10' viene prima di '2' nell'ordine dei codici Unicode code .
-
-var things = ['word', 'Word', '1 Word', '2 Words'];
-things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
-// In Unicode, i numeri vengono prima delle lettere maiuscole,
-// che vengono prima delle lettere minuscole.
-
- -

Sintassi

- -
arr.sort()
-arr.sort([compareFunction])
-
- -

Parametri

- -
-
compareFunction {{optional_inline}}
-
Specifica una funzione che definisce il tipo di ordinamento. Se viene omessa, l'array è ordinato in base ai valori dei suoi caratteri Unicode code , basandosi sulle stringhe di ogni elemento convertito.
-
- -

Valore ritornato

- -

L'array ordinato. Nota che l'array è ordinato in place, e non viene fatta alcuna copia.

- -

Descrizione

- -

Se non viene fornita una compareFunction , gli elementi vengono ordinati convertendoli in stringhe e confrontando le stringhe nell'ordine dei codici Unicode . Per esempio, "Banana" viene prima di "cherry". In ordine numerico, 9 arriva prima dell'80, ma poiché i numeri vengono convertiti in stringhe, "80" viene prima di "9" nell'ordine Unicode.

- -

Se viene fornita una compareFunction , gli elementi dell'array vengono ordinati in base al valore restituito della funzione di confronto. Se a e b sono due elementi da confrontare, allora:

- - - -

Quindi, la funzione di confronto ha la seguente forma:

- -
function compare(a, b) {
-  if (a è inferiore a b secondo un criterio di ordinamento) {
-    return -1;
-  }
-  if (a è maggiore di b secondo un criterio di ordinamento) {
-    return 1;
-  }
-  // a deve essere uguale a b
-  return 0;
-}
-
- -

Per confrontare i numeri anziché le stringhe, la funzione di confronto può semplicemente sottrarre b da a. La seguente funzione ordinerà l'array in ordine crescente (se non contiene Infinity e NaN):

- -
function compareNumbers(a, b) {
-  return a - b;
-}
-
- -

Il metodo sort può essere usato bene con {{jsxref("Operators/function", "function expressions", "", 1)}} ( e closures):

- -
var numbers = [4, 2, 5, 1, 3];
-numbers.sort(function(a, b) {
-  return a - b;
-});
-console.log(numbers);
-
-// [1, 2, 3, 4, 5]
-
- -

ES2015 fornisce le {{jsxref("Functions_and_function_scope/Arrow_functions", "arrow function", "", 1)}}, che consentono una sintassi più compatta:

- -
let numbers = [4, 2, 5, 1, 3];
-numbers.sort((a, b) => a - b);
-console.log(numbers);
-
-// [1, 2, 3, 4, 5]
- -

Gli Object possono essere ordinati passando il valore di una delle loro proprietà.

- -
var items = [
-  { name: 'Edward', value: 21 },
-  { name: 'Sharpe', value: 37 },
-  { name: 'And', value: 45 },
-  { name: 'The', value: -12 },
-  { name: 'Magnetic', value: 13 },
-  { name: 'Zeros', value: 37 }
-];
-
-// ordinamento per valore
-items.sort(function (a, b) {
-  return a.value - b.value;
-});
-
-// ordinamento per nome
-items.sort(function(a, b) {
-  var nameA = a.name.toUpperCase(); // ignora maiuscole e minuscole
-  var nameB = b.name.toUpperCase(); // ignora maiuscole e minuscole
-  if (nameA < nameB) {
-    return -1;
-  }
-  if (nameA > nameB) {
-    return 1;
-  }
-
-  // i nomi devono essere uguali
-  return 0;
-});
- -

Esempi

- -

Creare, visualizzare, ed ordinare un array

- -

L'esempio seguente crea quattro array , visualizza l'array originale e successivamente l'array ordinato. Gli array numerici sono ordinati prima senza e poi con una funzione di comparazione .

- -
var stringArray = ['Blue', 'Humpback', 'Beluga'];
-var numericStringArray = ['80', '9', '700'];
-var numberArray = [40, 1, 5, 200];
-var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
-
-function compareNumbers(a, b) {
-  return a - b;
-}
-
-console.log('stringArray:', stringArray.join());
-console.log('Ordinato:', stringArray.sort());
-
-console.log('numberArray:', numberArray.join());
-console.log('Ordinato senza funzione compare:', numberArray.sort());
-console.log('Ordinato con compareNumbers:', numberArray.sort(compareNumbers));
-
-console.log('numericStringArray:', numericStringArray.join());
-console.log('Ordinato senza funzione compare:', numericStringArray.sort());
-console.log('Ordinato con compareNumbers:', numericStringArray.sort(compareNumbers));
-
-console.log('mixedNumericArray:', mixedNumericArray.join());
-console.log('Ordinato senza funzione compare:', mixedNumericArray.sort());
-console.log('Ordinato con compareNumbers:', mixedNumericArray.sort(compareNumbers));
-
- -

Questo esempio produce il seguente output. Come viene mostrato, quando viene usata una funzione comparativa, i numeri vengono ordinati correttamente sia nel caso siano numeri che nel caso siano stringhe di numeri.

- -
stringArray: Blue,Humpback,Beluga
-Ordinato: Beluga,Blue,Humpback
-
-numberArray: 40,1,5,200
-Ordinato senza funzione compare: 1,200,40,5
-Ordinato con compareNumbers: 1,5,40,200
-
-numericStringArray: 80,9,700
-Ordinato senza funzione compare: 700,80,9
-Ordinato con compareNumbers: 9,80,700
-
-mixedNumericArray: 80,9,700,40,1,5,200
-Ordinato senza funzione compare: 1,200,40,5,700,80,9
-Ordinato con compareNumbers: 1,5,9,40,80,200,700
-
- -

Ordinare caratteri non-ASCII 

- -

Per ordinare stringhe con caratteri non-ASCII, cioè stringhe con caratteri accentati (e, é, è, a, ä, etc.), stringhe da lingue diverse dall'inglese: si usa {{jsxref("String.localeCompare")}}. Questa funzione può confrontare quei caratteri in modo che compaiano nel giusto ordine.

- -
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
-items.sort(function (a, b) {
-  return a.localeCompare(b);
-});
-
-// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
-
- -

Ordinare con map

- -

La compareFunction può essere invocata più volte per elemento all'interno dell'array. In base alla natura della compareFunction, si potrebbe produrre un sovraccarico elevato. Maggiore è il lavoro svolto da compareFunction e maggiori sono gli elementi da ordinare, potrebbe essere saggio utilizzare una map per l'ordinamento. L'idea è di percorrere una volta l'array per estrarre i valori effettivi usati per l'ordinamento in un array temporaneo, ordinare l'array temporaneo e quindi percorrere l'array temporaneo per ottenere l'ordine giusto.

- -
// l'array da ordinare
-var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
-
-// l'array temporaneo contiene oggetti con posizione e valore di ordinamento
-var mapped = list.map(function(el, i) {
-  return { index: i, value: el.toLowerCase() };
-})
-
-// ordinamento dell'array mappato contenente i valori ridotti
-mapped.sort(function(a, b) {
-  if (a.value > b.value) {
-    return 1;
-  }
-  if (a.value < b.value) {
-    return -1;
-  }
-  return 0;
-});
-
-// contenitore per l'ordine risultante
-var result = mapped.map(function(el){
-  return list[el.index];
-});
-
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoOsservazione
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ESDraft')}}
- -

Compatibilità con il browser

- -
- - -

{{Compat("javascript.builtins.Array.sort")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/splice/index.html b/files/it/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index a68058baf8..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -tags: - - Aggiunta - - Array - - JavaScript - - Method - - Prototype - - Reference - - Rimozione - - splice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -
{{JSRef}}
- -

Il metodo splice() modifica il contenuto di un array rimuovendo o sostituendo elementi esistenti e/o aggiungendo nuovi elementi in place.

- -
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
- - - -

Sintassi

- -
var arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
-
- -

Parametri

- -
-
start
-
L'indice al quale iniziare a cambiare l'array. Se maggiore della lunghezza dell'array, start sarà impostato sulla lunghezza dell'array. Se negativo, inizierà molti elementi dalla fine dell'array (con origine -1, che significa -n è l'indice dell'ultimo elemento dell'ennesima ed è quindi equivalente all'indice di array.length - n). Se il valore assoluto di  start è maggiore della lunghezza dell'array, inizierà dall'indice 0.
-
deleteCount {{optional_inline}}
-
Un numero intero che indica il numero di elementi nell'array da rimuovere da start.
-
Se deleteCount viene omesso, o se il suo valore è uguale o maggiore di array.length - start (cioè, se è uguale o maggiore del numero di elementi rimasti nell'array, a partire da start), tutti gli elementi da start alla fine dell'array verranno eliminati.
-
Se deleteCount è 0 o negativo, non vengono rimossi elementi. In questo caso, devi specificare almeno un nuovo elemento (vedi sotto).
-
item1, item2, ... {{optional_inline}}
-
Gli elementi da aggiungere all'array, a partire da start. Se non viene specificato alcun elemento, splice() rimuoverà solo gli elementi dall'array.
-
- -

Valore di ritorno

- -

Un array contenente gli elementi eliminati. Se viene rimosso solo un elemento, viene restituito un array di un elemento. Se non vengono rimossi elementi, viene restituito un array vuoto.

- -

Descrizione

- -

Se il numero specificato di elementi da inserire differisce dal numero di elementi da rimuovere, la lunghezza dell'array sarà diversa alla fine della chiamata.

- -

Esempi

- -

Rimuovi 0 (zero) elementi dall'indice 2 e inserisci "drum"

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum');
-
-// myFish è ["angel", "clown", "drum", "mandarin", "sturgeon"]
-// removed è [], nessun elemento rimosso
- -

Rimuovi 0 (zero) elementi dall'indice 2 e inserisci "drum" e "guitar"

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum', 'guitar');
-
-// myFish è ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
-// removed è [], nessun elemento rimosso
-
- -

Rimuovi 1 elemento dall'indice 3

- -
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(3, 1);
-
-// removed è ["mandarin"]
-// myFish è ["angel", "clown", "drum", "sturgeon"]
-
- -

Rimuovi 1 elemento dall'indice 2 e inserisci "trumpet"

- -
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
-var removed = myFish.splice(2, 1, 'trumpet');
-
-// myFish è ["angel", "clown", "trumpet", "sturgeon"]
-// removed è ["drum"]
- -

Rimuovere 2 elementi dall'indice 0 e inserire "parrot", "anemone" e "blue"

- -
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
-
-// myFish è ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
-// removed è ["angel", "clown"]
- -

Rimuovere 2 elementi dall'indice 2

- -
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(myFish.length - 3, 2);
-
-// myFish è ["parrot", "anemone", "sturgeon"]
-// removed è ["blue", "trumpet"]
- -

Rimuovere 1 elemento dall'indice -2

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(-2, 1);
-
-// myFish è ["angel", "clown", "sturgeon"]
-// removed è ["mandarin"]
- -

Rimuovere tutti gli elementi dopo l'indice 2 (incl.)

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2);
-
-// myFish è ["angel", "clown"]
-// removed è ["mandarin", "sturgeon"]
- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale Implementato in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}}
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.splice")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/tostring/index.html b/files/it/web/javascript/reference/global_objects/array/tostring/index.html deleted file mode 100644 index a5b8dcaa1e..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/tostring/index.html +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Array.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Array/toString -tags: - - Array - - JavaScript - - Prototype - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString ---- -
{{JSRef}}
- -

Il metodo toString() restituisce una stringa che rappresenta l'array specificato e i suoi elementi.

- -
{{EmbedInteractiveExample("pages/js/array-tostring.html")}}
- -

Sintassi

- -
arr.toString()
- -

Valore di ritorno

- -

Una stringa che rappresenta gli elementi dell'array.

- -

Descrizione

- -

L'oggetto {{jsxref("Array")}} sovrascrive il metodo toString di {{jsxref("Object")}}. Per gli oggetti Array, il metodo toString unisce l'array e restituisce una stringa contenente ciascun elemento dell'array separato da virgole.

- -

JavaScript chiama automaticamente il metodo toString quando un array deve essere rappresentato come un valore di testo o quando viene fatto riferimento a un array in una concatenazione di stringhe.

- -

ECMAScript 5 semantics

- -

A partire da JavaScript 1.8.5 (Firefox 4) e coerente con la semantica ECMAScript 5th edition, il metodo toString() è generico e può essere utilizzato con qualsiasi oggetto. {{jsxref("Object.prototype.toString()")}} sarà chiamato e verrà restituito il valore risultante.

- -

Specifiche

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale Implementato in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.2', 'Array.prototype.toString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ESDraft')}} 
- -

Compatibilità con i browser

- -
- - -

{{Compat("javascript.builtins.Array.toString")}}

-
- -

Vedi anche

- - diff --git a/files/it/web/javascript/reference/global_objects/array/unshift/index.html b/files/it/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index ca4597e973..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -
{{JSRef}}
- -
Il metodo unshift() aggiunge uno o più elementi all'inizio di un array e restitusce la nuova lunghezza dell'array stesso.
- -
 
- -
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
- -

Sintassi

- -
arr.unshift(element1[, ...[, elementN]])
- -

Parameters

- -
-
elementN
-
Gli elementi da aggiungere all'inizio dell'array.
-
- -

Return value

- -
-
La nuova proprietà {{jsxref("Array.length", "length")}} dell'oggetto su cui è stato chiamato il metodo.
-
- -

Descrizione

- -

Il metodo unshift inserisce i valori passati come parametri all'inizio di un oggetto array-like.

- -

unshift è instenzionalmente generico; questo metodo può essere {{jsxref("Function.call", "chiamato", "", 1)}} o {{jsxref("Function.apply", "applicato", "", 1)}} su oggetti che assomigliano ad un array. Oggetti che non contengono una proprietà length che rifletta l'ultimo di una serie di consecutive proprietà numeriche zero-based potrebbero non comportarsi in alcun modo significativo.

- -

Esempi

- -
var arr = [1, 2];
-
-arr.unshift(0); // result of call is 3, the new array length
-// arr is [0, 1, 2]
-
-arr.unshift(-2, -1); // = 5
-// arr is [-2, -1, 0, 1, 2]
-
-arr.unshift([-3]);
-// arr is [[-3], -2, -1, 0, 1, 2]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.unshift")}}

-
- -

See also

- - diff --git a/files/it/web/javascript/reference/global_objects/array/values/index.html b/files/it/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index f3019ef144..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -
{{JSRef}}
- -

 

- -

Il metodo values() restituisce un nuovo oggetto Array Iterator che contiene i valori per ogni indice nell'array.

- -

{{EmbedInteractiveExample("pages/js/array-values.html")}}

- -
var a = ['a', 'b', 'c', 'd', 'e'];
-var iterator = a.values();
-
-console.log(iterator.next().value); // a
-console.log(iterator.next().value); // b
-console.log(iterator.next().value); // c
-console.log(iterator.next().value); // d
-console.log(iterator.next().value); // e
- -

Sintassi

- -
arr.values()
- -

Valore di ritorno

- -

Un nuovo oggetto iteratore {{jsxref("Array")}}.

- -

Esempi

- -

Iterazione utilizzando il  for...of loop

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
-var iterator = arr.values();
-
-for (let letter of iterator) {
-  console.log(letter);
-}
-
- -

Array.prototype.values è una implementazionde di default di Array.prototype[Symbol.iterator].

- -
Array.prototype.values === Array.prototype[Symbol.iterator]      //true
- -

TODO: please write about why we need it, use cases.

- -

Specificazioni

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.values")}}

-
- -

See also

- - -- cgit v1.2.3-54-g00ecf