From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../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 +++++ .../global_objects/array/prototype/index.html | 203 ++++++++ .../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 ++++ .../global_objects/arraybuffer/index.html | 147 ++++++ .../reference/global_objects/atomics/index.html | 166 ++++++ .../global_objects/atomics/store/index.html | 91 ++++ .../global_objects/date/getdate/index.html | 78 +++ .../global_objects/date/getday/index.html | 89 ++++ .../global_objects/date/getfullyear/index.html | 84 +++ .../global_objects/date/gethours/index.html | 79 +++ .../global_objects/date/getmilliseconds/index.html | 77 +++ .../global_objects/date/getminutes/index.html | 77 +++ .../global_objects/date/getmonth/index.html | 90 ++++ .../global_objects/date/getseconds/index.html | 79 +++ .../global_objects/date/gettime/index.html | 125 +++++ .../date/gettimezoneoffset/index.html | 99 ++++ .../reference/global_objects/date/index.html | 249 +++++++++ .../reference/global_objects/date/now/index.html | 96 ++++ .../reference/global_objects/date/utc/index.html | 135 +++++ .../reference/global_objects/decodeuri/index.html | 120 +++++ .../global_objects/decodeuricomponent/index.html | 124 +++++ .../reference/global_objects/encodeuri/index.html | 160 ++++++ .../global_objects/encodeuricomponent/index.html | 162 ++++++ .../reference/global_objects/escape/index.html | 126 +++++ .../reference/global_objects/eval/index.html | 231 +++++++++ .../global_objects/function/apply/index.html | 250 +++++++++ .../global_objects/function/arguments/index.html | 92 ++++ .../global_objects/function/arity/index.html | 26 + .../global_objects/function/bind/index.html | 277 ++++++++++ .../global_objects/function/call/index.html | 175 +++++++ .../reference/global_objects/function/index.html | 237 +++++++++ .../global_objects/function/length/index.html | 87 ++++ .../reference/global_objects/generator/index.html | 187 +++++++ .../global_objects/generator/next/index.html | 157 ++++++ .../javascript/reference/global_objects/index.html | 182 +++++++ .../reference/global_objects/infinity/index.html | 114 ++++ .../reference/global_objects/isfinite/index.html | 136 +++++ .../reference/global_objects/isnan/index.html | 176 +++++++ .../reference/global_objects/json/index.html | 244 +++++++++ .../reference/global_objects/json/parse/index.html | 126 +++++ .../global_objects/json/stringify/index.html | 325 ++++++++++++ .../reference/global_objects/map/clear/index.html | 76 +++ .../reference/global_objects/map/delete/index.html | 74 +++ .../global_objects/map/foreach/index.html | 88 ++++ .../reference/global_objects/map/index.html | 439 ++++++++++++++++ .../reference/global_objects/math/abs/index.html | 95 ++++ .../reference/global_objects/math/acos/index.html | 94 ++++ .../reference/global_objects/math/atan/index.html | 100 ++++ .../reference/global_objects/math/atan2/index.html | 155 ++++++ .../reference/global_objects/math/ceil/index.html | 161 ++++++ .../reference/global_objects/math/e/index.html | 79 +++ .../reference/global_objects/math/floor/index.html | 158 ++++++ .../reference/global_objects/math/index.html | 208 ++++++++ .../reference/global_objects/math/max/index.html | 145 ++++++ .../reference/global_objects/math/min/index.html | 160 ++++++ .../reference/global_objects/math/pow/index.html | 151 ++++++ .../global_objects/math/random/index.html | 107 ++++ .../reference/global_objects/math/round/index.html | 100 ++++ .../reference/global_objects/math/sqrt/index.html | 136 +++++ .../reference/global_objects/nan/index.html | 79 +++ .../reference/global_objects/null/index.html | 89 ++++ .../reference/global_objects/number/index.html | 188 +++++++ .../global_objects/object/assign/index.html | 268 ++++++++++ .../global_objects/object/create/index.html | 234 +++++++++ .../object/defineproperties/index.html | 224 ++++++++ .../global_objects/object/freeze/index.html | 210 ++++++++ .../object/getprototypeof/index.html | 130 +++++ .../object/hasownproperty/index.html | 164 ++++++ .../reference/global_objects/object/index.html | 224 ++++++++ .../reference/global_objects/object/is/index.html | 130 +++++ .../global_objects/object/isfrozen/index.html | 184 +++++++ .../global_objects/object/issealed/index.html | 146 ++++++ .../global_objects/object/keys/index.html | 167 ++++++ .../global_objects/object/observe/index.html | 189 +++++++ .../global_objects/object/prototype/index.html | 214 ++++++++ .../global_objects/object/seal/index.html | 157 ++++++ .../global_objects/object/tostring/index.html | 170 ++++++ .../reference/global_objects/parsefloat/index.html | 139 +++++ .../reference/global_objects/parseint/index.html | 190 +++++++ .../global_objects/promise/all/index.html | 110 ++++ .../global_objects/promise/catch/index.html | 124 +++++ .../reference/global_objects/promise/index.html | 248 +++++++++ .../global_objects/proxy/handler/apply/index.html | 119 +++++ .../global_objects/proxy/handler/index.html | 83 +++ .../reference/global_objects/proxy/index.html | 396 ++++++++++++++ .../global_objects/proxy/revocabile/index.html | 86 +++ .../global_objects/set/entries/index.html | 113 ++++ .../reference/global_objects/set/index.html | 394 ++++++++++++++ .../reference/global_objects/set/values/index.html | 114 ++++ .../global_objects/string/charat/index.html | 247 +++++++++ .../global_objects/string/includes/index.html | 188 +++++++ .../reference/global_objects/string/index.html | 410 +++++++++++++++ .../global_objects/string/indexof/index.html | 151 ++++++ .../global_objects/string/length/index.html | 90 ++++ .../global_objects/string/prototype/index.html | 178 +++++++ .../reference/global_objects/string/raw/index.html | 108 ++++ .../reference/global_objects/symbol/index.html | 230 ++++++++ .../reference/global_objects/undefined/index.html | 173 +++++++ .../reference/global_objects/unescape/index.html | 124 +++++ .../reference/global_objects/uneval/index.html | 112 ++++ 131 files changed, 21805 insertions(+) create mode 100644 files/it/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/flatmap/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/prototype/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/tostring/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/it/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/it/web/javascript/reference/global_objects/atomics/index.html create mode 100644 files/it/web/javascript/reference/global_objects/atomics/store/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/gethours/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getminutes/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getmonth/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getseconds/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/gettime/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/it/web/javascript/reference/global_objects/decodeuri/index.html create mode 100644 files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html create mode 100644 files/it/web/javascript/reference/global_objects/encodeuri/index.html create mode 100644 files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html create mode 100644 files/it/web/javascript/reference/global_objects/escape/index.html create mode 100644 files/it/web/javascript/reference/global_objects/eval/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/arity/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/it/web/javascript/reference/global_objects/generator/index.html create mode 100644 files/it/web/javascript/reference/global_objects/generator/next/index.html create mode 100644 files/it/web/javascript/reference/global_objects/index.html create mode 100644 files/it/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/it/web/javascript/reference/global_objects/isfinite/index.html create mode 100644 files/it/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/it/web/javascript/reference/global_objects/json/index.html create mode 100644 files/it/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/it/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/clear/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/delete/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/foreach/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/acos/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/atan/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/atan2/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/sqrt/index.html create mode 100644 files/it/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/it/web/javascript/reference/global_objects/null/index.html create mode 100644 files/it/web/javascript/reference/global_objects/number/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/is/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/isfrozen/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/issealed/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/observe/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/seal/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/it/web/javascript/reference/global_objects/parsefloat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/parseint/index.html create mode 100644 files/it/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/it/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/it/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/handler/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html create mode 100644 files/it/web/javascript/reference/global_objects/set/entries/index.html create mode 100644 files/it/web/javascript/reference/global_objects/set/index.html create mode 100644 files/it/web/javascript/reference/global_objects/set/values/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/charat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/includes/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/raw/index.html create mode 100644 files/it/web/javascript/reference/global_objects/symbol/index.html create mode 100644 files/it/web/javascript/reference/global_objects/undefined/index.html create mode 100644 files/it/web/javascript/reference/global_objects/unescape/index.html create mode 100644 files/it/web/javascript/reference/global_objects/uneval/index.html (limited to 'files/it/web/javascript/reference/global_objects') 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 new file mode 100644 index 0000000000..9d8d7d6629 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,188 @@ +--- +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 new file mode 100644 index 0000000000..65e00abe47 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,180 @@ +--- +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 new file mode 100644 index 0000000000..31e156afb8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,77 @@ +--- +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 new file mode 100644 index 0000000000..c1f3238ad6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,184 @@ +--- +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 new file mode 100644 index 0000000000..043696f554 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,155 @@ +--- +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 new file mode 100644 index 0000000000..33d24d38b6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,245 @@ +--- +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 new file mode 100644 index 0000000000..c215ff79e7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,216 @@ +--- +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 new file mode 100644 index 0000000000..f9f2f65791 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,182 @@ +--- +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 new file mode 100644 index 0000000000..3c5a81ed4b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,159 @@ +--- +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 new file mode 100644 index 0000000000..4397fd7c5d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/flatmap/index.html @@ -0,0 +1,142 @@ +--- +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 new file mode 100644 index 0000000000..dbd4919852 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,331 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Prototype + - Referenza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +
{{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 new file mode 100644 index 0000000000..83baed1267 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,242 @@ +--- +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 new file mode 100644 index 0000000000..04dc817974 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,162 @@ +--- +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 new file mode 100644 index 0000000000..844d1baf00 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,480 @@ +--- +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 new file mode 100644 index 0000000000..658957c67d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,226 @@ +--- +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 new file mode 100644 index 0000000000..d7aaf864bf --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,133 @@ +--- +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 new file mode 100644 index 0000000000..8483c817ac --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,112 @@ +--- +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 new file mode 100644 index 0000000000..78212d221f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,74 @@ +--- +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 new file mode 100644 index 0000000000..c4170455f6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html @@ -0,0 +1,169 @@ +--- +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 new file mode 100644 index 0000000000..a36a6b5204 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,129 @@ +--- +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 new file mode 100644 index 0000000000..808b4fc728 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,323 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - JavaScript + - Prototype + - Referenza + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +
{{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 new file mode 100644 index 0000000000..808c1dda2c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,92 @@ +--- +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 new file mode 100644 index 0000000000..6feabb5f14 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,117 @@ +--- +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/prototype/index.html b/files/it/web/javascript/reference/global_objects/array/prototype/index.html new file mode 100644 index 0000000000..d4989792a8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/prototype/index.html @@ -0,0 +1,203 @@ +--- +title: Array.prototype +slug: Web/JavaScript/Reference/Global_Objects/Array/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/prototype +--- +
{{JSRef}}
+ +

La proprietà Array.prototype rappresenta il prototipo per il costruttore {{jsxref("Array")}} .

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrizione

+ +

Le istanze {{jsxref("Array")}} ereditano da Array.prototype. Come con gli altri costruttori, si può cambiare il prototipo propagando i cambiamenti su tutte le sue istanze.

+ +

Piccola curiosità: Array.prototype è un {{jsxref("Array")}}:

+ +
Array.isArray(Array.prototype); // true
+
+ +

Proprietà

+ +
+
Array.prototype.constructor
+
Restituisce il costruttore.
+
{{jsxref("Array.prototype.length")}}
+
Restituisce il numero di elementi in un array.
+
+ +

Metodi

+ +

Metodi mutator

+ +

Questi metodi modificano l'array:

+ +
+
{{jsxref("Array.prototype.copyWithin()")}} {{experimental_inline}}
+
Copia una sequenza di elementi dell'array all'interno dello stesso.
+
{{jsxref("Array.prototype.fill()")}} {{experimental_inline}}
+
Riempie le posizioni dell'array contenute tra 2 indici con un valore fisso.
+
{{jsxref("Array.prototype.pop()")}}
+
Rimuove e restituisce l'ultimo elemento dell'array.
+
{{jsxref("Array.prototype.push()")}}
+
Accoda uno o più elementi all'array e restituisce la lunghezza aggiornata dello stesso.
+
{{jsxref("Array.prototype.reverse()")}}
+
Inverte l'ordine delle posizioni degli elementi all'interno dell'array.
+
{{jsxref("Array.prototype.shift()")}}
+
Rimuove e resistuisce il primo elemento di un array.
+
{{jsxref("Array.prototype.sort()")}}
+
Ordina gli elementi di un array all'interno di esso e restituisce l'array.
+
{{jsxref("Array.prototype.splice()")}}
+
Aggiunge e/o rimuove elementi da un array.
+
{{jsxref("Array.prototype.unshift()")}}
+
Aggiunge uno o più elementi all'inizio di un array e restituisce la lunghezza aggiornata dello stesso.
+
+ +

Metodi accessor

+ +

Questi metodi non modificano l'array e ne restituiscono una sua rappresentazione.

+ +
+
{{jsxref("Array.prototype.concat()")}}
+
Restituisce un nuovo array costituito dall'array stesso insieme ad altri array/valori.
+
{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}
+
Restituisce true se l'array contiene un certo elemento, false altrimenti.
+
{{jsxref("Array.prototype.join()")}}
+
Resituisce i valori dell'array come stringa.
+
{{jsxref("Array.prototype.slice()")}}
+
Restituisce un nuovo array cosituito da elementi dell'array originale.
+
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
+
Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("Array.prototype.toString()")}}
+
Returns a string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("Array.prototype.toLocaleString()")}}
+
Returns a localized string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
+
{{jsxref("Array.prototype.indexOf()")}}
+
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
+
{{jsxref("Array.prototype.lastIndexOf()")}}
+
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
+
+ +

Iteration methods

+ +

Several methods take as arguments functions to be called back while processing the array. When these methods are called, the length of the array is sampled, and any element added beyond this length from within the callback is not visited. Other changes to the array (setting the value of or deleting an element) may affect the results of the operation if the method visits the changed element afterwards. While the specific behavior of these methods in such cases is well-defined, you should not rely upon it so as not to confuse others who might read your code. If you must mutate the array, copy into a new array instead.

+ +
+
{{jsxref("Array.prototype.forEach()")}}
+
Calls a function for each element in the array.
+
{{jsxref("Array.prototype.entries()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
+
{{jsxref("Array.prototype.every()")}}
+
Returns true if every element in this array satisfies the provided testing function.
+
{{jsxref("Array.prototype.some()")}}
+
Returns true if at least one element in this array satisfies the provided testing function.
+
{{jsxref("Array.prototype.filter()")}}
+
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
+
{{jsxref("Array.prototype.find()")}} {{experimental_inline}}
+
Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
+
{{jsxref("Array.prototype.findIndex()")}} {{experimental_inline}}
+
Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
+
{{jsxref("Array.prototype.keys()")}} {{experimental_inline}}
+
Returns a new Array Iterator that contains the keys for each index in the array.
+
{{jsxref("Array.prototype.map()")}}
+
Creates a new array with the results of calling a provided function on every element in this array.
+
{{jsxref("Array.prototype.reduce()")}}
+
Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
+
{{jsxref("Array.prototype.reduceRight()")}}
+
Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
+
{{jsxref("Array.prototype.values()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the values for each index in the array.
+
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the values for each index in the array.
+
+ +

Generic methods

+ +

Many methods on the JavaScript Array object are designed to be generally applied to all objects which “look like” Arrays. That is, they can be used on any object which has a length property, and which can usefully be accessed using numeric property names (as with array[5] indexing). TODO: give examples with Array.prototype.forEach.call, and adding the method to an object like {{jsxref("Global_Objects/JavaArray", "JavaArray")}} or {{jsxref("Global_Objects/String", "String")}}. Some methods, such as {{jsxref("Array.join", "join")}}, only read the length and numeric properties of the object they are called on. Others, like {{jsxref("Array.reverse", "reverse")}}, require that the object's numeric properties and length be mutable; these methods can therefore not be called on objects like {{jsxref("String")}}, which does not permit its length property or synthesized numeric properties to be set.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.3.1', 'Array.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

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

See also

+ + 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 new file mode 100644 index 0000000000..ad34c3da2d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,142 @@ +--- +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 new file mode 100644 index 0000000000..de063df929 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,576 @@ +--- +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 new file mode 100644 index 0000000000..750befde61 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,133 @@ +--- +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 new file mode 100644 index 0000000000..419da77ae4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,241 @@ +--- +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 new file mode 100644 index 0000000000..3befa8a8b0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,202 @@ +--- +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 new file mode 100644 index 0000000000..6c16c7dd6b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,267 @@ +--- +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 new file mode 100644 index 0000000000..a68058baf8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,163 @@ +--- +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 new file mode 100644 index 0000000000..a5b8dcaa1e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/tostring/index.html @@ -0,0 +1,80 @@ +--- +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 new file mode 100644 index 0000000000..ca4597e973 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,98 @@ +--- +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 new file mode 100644 index 0000000000..f3019ef144 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,87 @@ +--- +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

+ + diff --git a/files/it/web/javascript/reference/global_objects/arraybuffer/index.html b/files/it/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..118b3d2801 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,147 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +tags: + - Array tipizzati + - ArrayBuffer + - Constructor + - Costruttore + - JavaScript + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +
{{JSRef}}
+ +

L'oggetto ArrayBuffer viene utilizzato per rappresentare un buffer di lunghezza fissa di dati non elaborati. Non è possibile manipolare il contenuto di un ArrayBuffer, è possibile invece creare un array di oggetti tipizzati o un oggetto di tipo {{jsxref("DataView")}} che rappresenta il buffer in uno specifico formato ed utilizzare questo per leggere e scrivere il contenuto del buffer.

+ +
{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}
+ + + +

Sintassi

+ +
new ArrayBuffer(length)
+
+ +

Parametri

+ +
+
length
+
La dimensione, in bytes, dell'array buffer da creare.
+
+ +

Valori di ritorno

+ +

Un nuovo oggetto di tipo ArrayBuffer della dimensione specificata. Il suo contenuto è inzializzato a 0.

+ +

Eccezioni

+ +

Un {{jsxref("RangeError")}} viene generato se la lunghezza è maggiore di di {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) oppure è negativa.

+ +

Descrizione

+ +

Il costruttore ArrayBuffer crea un nuovo ArrayBuffer di lunghezza specificata in bytes.

+ +

Ottenere un array buffer da dati pre-esistenti

+ + + +

Proprietà

+ +
+
ArrayBuffer.length
+
La dimensione del costruttore ArrayBuffer il cui valore è 1.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
La funzione costruttore utilizzata per creare oggetti derivati.
+
{{jsxref("ArrayBuffer.prototype")}}
+
Permette di aggiungere proprietà a tutti gli oggetti di tipo ArrayBuffer.
+
+ +

Metodi

+ +
+
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
+
Restituisce true se args è una delle viste di ArrayBuffer, come un array di oggetti tipizzato o un {{jsxref("DataView")}}. Altrimenti restituisce false.
+
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
+
Restituisce un nuovo ArrayBuffer i cui contenuti sono presi dai dati dell'oggetto oldBuffer e successivamente troncato o esteso a zero tramite newByteLength.
+
+ +

Istanze

+ +

Tutte le istanze di ArrayBuffer ereditano da {{jsxref("ArrayBuffer.prototype")}}.

+ +

Proprietà

+ +

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

+ +

Metodi

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}

+ +
+
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
+
Esegue le stesse operazioni di {{jsxref("ArrayBuffer.prototype.slice()")}}.
+
+ +

Esempio

+ +

In questo esempio viene creato un buffer di 8 byte con una vista di tipo {{jsxref("Global_Objects/Int32Array", "Int32Array")}} che si riferisce al buffer

+ +
var buffer = new ArrayBuffer(8);
+var view   = new Int32Array(buffer);
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Sostituito da ECMAScript 6.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}} +

Definizione iniziale con standard ECMA. Specifica che new è richiesto.

+
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.ArrayBuffer")}}

+ +

Note sulla compatibilità

+ +

Con ECMAScript 2015, ArrayBuffer deve essere inizializzato con l'operatore  {{jsxref("Operators/new", "new")}}. Inizializzare ArrayBuffer senza l'operatore new genererà un {{jsxref("TypeError")}}.

+ +
var dv = ArrayBuffer(10);
+// TypeError: inizializzaree un ArrayBuffer senza il costruttore new
+// genererà un errore
+
+ +
var dv = new ArrayBuffer(10);
+ +

Leggi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/atomics/index.html b/files/it/web/javascript/reference/global_objects/atomics/index.html new file mode 100644 index 0000000000..56c3ed5ecc --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/atomics/index.html @@ -0,0 +1,166 @@ +--- +title: Atomics +slug: Web/JavaScript/Reference/Global_Objects/Atomics +translation_of: Web/JavaScript/Reference/Global_Objects/Atomics +--- +
{{JSRef}}
+ +

L' oggetto Atomics fornisce operazioni atomiche come metodi statici. Sono utilizzati con gli oggetti {{jsxref("SharedArrayBuffer")}}.

+ +

Le operazioni atomiche sono implementate nel modulo Atomics. Diversamente dagli altri oggetti global, Atomics non è un constructor. Non è, quindi, possibile utilizzarlo con new operator o invocare l'oggetto Atomics come una funzione. Tutte le proprietà ed i metodi di Atomics sono statici (come per esempio nel caso dell'oggetto {{jsxref("Math")}}).

+ +

Propertà

+ +
+
Atomics[Symbol.toStringTag]
+
Il valore di questa proprietà è "Atomics".
+
+ +

Metodi

+ +

Operazioni Atomiche

+ +

Quando la memoria è condivisa, molti thread possono leggere e scrivere gli stessi dati in memoria. Le operazioni atomiche fanno in modo che: siano scritti e letti valori predicibili, che ciscuna operazione termini prima che la successiva abbia inizio e che ciascuna operazione non sia interrotta.

+ +
+
{{jsxref("Atomics.add()")}}
+
Aggiunge un determinato valore in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.and()")}}
+
Calcola un "bitwise AND" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.compareExchange()")}}
+
Memorizza un dato valore in una posizione dell'array, se questo valore è uguale ad un altro determinato valore. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.exchange()")}}
+
Memorizza un dato valore in una determinata posizione nell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
+ +
+
{{jsxref("Atomics.load()")}}
+
Restituisce il valore di una determinata posizione nell'array.
+
{{jsxref("Atomics.or()")}}
+
Calcola un "bitwise OR" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.store()")}}
+
Memorizza un dato valore in una determinata posizione dell'array. Restituisce lo stesso valore momorizzato.
+
{{jsxref("Atomics.sub()")}}
+
Sottrae un determinato valore ad una data posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.xor()")}}
+
Calcola un "bitwise XOR" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
+ +

Wait and wake

+ +

I metodi wait() e wake() sono modellati sul futexes ("fast user-space mutex") di Linux e forniscono metodi di attesa finchè una certa condizione non diventa vera e sono tipicamente utilizzati in costrutti bloccanti.

+ +
+
{{jsxref("Atomics.wait()")}}
+
+

Verifica che una certa posizione dell'array continui a contenere un determinato valore e si mette in attesa o va in time-out. Restituisce i valori "ok", "not-equal", oppure "timed-out". Se l'attesa non è consentita dall'agente che effettua la chiamata, allora il metodo innesca una "Error Exception" (molti browsers non consentiranno wait() nel loro thread principale)

+
+
{{jsxref("Atomics.wake()")}}
+
"Sveglia" gli agenti dormienti nella coda di wait in una determinata posizione dell'array. Restituisce il numero degli agenti "svegliati".
+
{{jsxref("Atomics.isLockFree()", "Atomics.isLockFree(size)")}}
+
+

Un primitiva di ottimizzazione che può essere utilizzata per determinare quando utilizzare "lock" o operazioni atomiche. Restituisce true, se un operazione atomica su un array di una data dimensione può essere implementata utilizzando operazioni atomiche hardware (invece del "lock"). Solo per esperti.

+
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatusCommenti
{{SpecName('ESDraft', '#sec-atomics-object', 'Atomics')}}{{Spec2('ESDraft')}}Definizione Iniziale in ES2017.
{{SpecName('ES8', '#sec-atomics-object', 'Atomics')}}{{Spec2('ES8')}} 
+ +

Compatibilità con i Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}} [2]{{CompatGeckoDesktop("55")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("55")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] In Firefox, dalla versione 46 alla versione 54 questa feature è disabilitata da una configurazione avenzata. In about:config, configurare javascript.options.shared_memory a true

+ +

[2] L' implementazione è in via di sviluppo e richiede i flag di runtime: --js-flags=--harmony-sharedarraybuffer --enable-blink-feature=SharedArrayBuffer

+ +

Note di Compatibilità

+ +

Prima di SpiderMonkey 48 {{geckoRelease(48)}}, i nomi e le semantiche delle API non erano ancora state implementate. Le modifiche tra la versione 46 e la versione 48 di Firefox, sono:

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/atomics/store/index.html b/files/it/web/javascript/reference/global_objects/atomics/store/index.html new file mode 100644 index 0000000000..5c8a466c0f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/atomics/store/index.html @@ -0,0 +1,91 @@ +--- +title: Atomics.store() +slug: Web/JavaScript/Reference/Global_Objects/Atomics/store +tags: + - Atomics + - JavaScript + - Memoria condivisa + - Store + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Atomics/store +--- +
{{JSRef}}
+ +

Il metodo statico Atomics.store() memorizza un determinato valore nella posizione data nell'array e restituisce quel valore.

+ +
{{EmbedInteractiveExample("pages/js/atomics-store.html")}}
+ + + +

Sintassi

+ +
Atomics.store(typedArray, indice, valore)
+
+ +

Parameters

+ +
+
typedArray
+
Un array con numero intero condiviso. Uno di {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, o {{jsxref("Uint32Array")}}.
+
indice
+
La posizione in typedArray per memorizzare un  value in.
+
valore
+
Numero da memorizzare.
+
+ +

Valore di Ritorno

+ +

The value that has been stored
+ // Il valore memorizzato.

+ +

Eccezioni

+ + + +

Esempio

+ +
var buffer = new ArrayBuffer(4);         // common buffer
+var float32 = new Float32Array(buffer);  // floating point
+var uint32 = new Uint32Array(buffer);    // IEEE754 representation
+
+float32[0] = 0.5;
+console.log("0x" + uint32[0].toString(16));
+
+uint32[0] = 0x3f000000;   /// IEEE754 32-bit representation of 0.5
+console.log(float32[0]);
+
+
+ +

Specificazioni

+ + + + + + + + + + + + + + +
SpecificazioniStatoCommenti
{{SpecName('ESDraft', '#sec-atomics.store', 'Atomics.store')}}{{Spec2('ESDraft')}}definizione inizile in ES2017.
+ +

Browser compatibili

+ + + +

{{Compat("javascript.builtins.Atomics.store")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getdate/index.html b/files/it/web/javascript/reference/global_objects/date/getdate/index.html new file mode 100644 index 0000000000..32c3d5fa57 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getdate/index.html @@ -0,0 +1,78 @@ +--- +title: Date.prototype.getDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate +--- +
{{JSRef}}
+ +

Il metodo getDate()  resituisce il giorno del mese per la data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getdate.html")}}
+ + + +

Sintassi

+ +
dateObj.getDate()
+ +

Valore di ritorno

+ +

Un numero  integer,  tra 1 e 31, rappresentante il giorno del mese per la data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando getDate()

+ +

La seconda dichiarazione qui sotto assegna il valore 25 alla variabile day,  basata sul valore dell'oggetto {{jsxref("Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var day = Xmas95.getDate();
+
+console.log(day); // 25
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.1.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getDate")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getday/index.html b/files/it/web/javascript/reference/global_objects/date/getday/index.html new file mode 100644 index 0000000000..c5fd48bca7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getday/index.html @@ -0,0 +1,89 @@ +--- +title: Date.prototype.getDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDay +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay +--- +
{{JSRef}}
+ +

Il metodo getDay()  restituisce il giorno della settimana per la data specificata in accordo con l'ora locale, dove 0 rappresenta Domenica. Per il giorno del mese, vedere {{jsxref("Date.prototype.getDate()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-getday.html")}}
+ + + +

Sintassi

+ +
dateObj.getDay()
+ +

Valore di ritorno

+ +

Un numero di tipo  integer,  tra 0 e 6, corrispondente al giorno della settimana per la data fornita, in accordo con l'ora locale: 0 for Domenica, 1 per Lunedi, 2 for Martedi e cosi' via.

+ +

Esempi

+ +

Utilizzando  getDay()

+ +

La seconda dichiarazione qui sotto assegna il valore 1 a weekday, basato sul valore dell'oggetto {{jsxref("Date")}} Xmas95. December 25, 1995, è un Lunedi.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var weekday = Xmas95.getDay();
+
+console.log(weekday); // 1
+
+ +
+

Note: Se necessitato il nome completo di un giorno ("Monday" per esempio ) può essere ottenuto utilizzando {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} con un parametro options . Utilizzando questo metodo,  l'internazionalizzazione risulta più semplice:

+ +
var options = { weekday: 'long'};
+console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95));
+// Monday
+console.log(new Intl.DateTimeFormat('de-DE', options).format(Xmas95));
+// Montag
+
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.16', 'Date.prototype.getDay')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getDay")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/it/web/javascript/reference/global_objects/date/getfullyear/index.html new file mode 100644 index 0000000000..57d1c5efc7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getfullyear/index.html @@ -0,0 +1,84 @@ +--- +title: Date.prototype.getFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +--- +
{{JSRef}}
+ +

 

+ +

Il metodo  getFullYear() restituisce l'anno della data specificata in accordo con l'ora locale.

+ +

Utilizza questo metodo invece di quello {{jsxref("Date.prototype.getYear()", "getYear()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}
+ + + +

Sintassi

+ +
dateObj.getFullYear()
+ +

Valore di ritorno

+ +

Un numero corrispondente all'anno della data fornita, in accordo con l'ora locale.

+ +

Descrizione

+ +

Il valore restituito da getFullYear() è un numero assoluto. Per le date tra gli anni 1000 e 9999, getFullYear() restituisce un numero a 4 cifre, per esempio, 1995. Usa quetsa funzione per essere sicuro che un anno sia compiacente con gli anni dopo il 2000.

+ +

Esempi

+ +

Utilizzando getFullYear()

+ +

Il seguente esempio assegna il valore a quattro cifre dell'anno corrente alla variabile year.

+ +
var today = new Date();
+var year = today.getFullYear();
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Date.getFullYear")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/gethours/index.html b/files/it/web/javascript/reference/global_objects/date/gethours/index.html new file mode 100644 index 0000000000..7e04a04d3f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/gethours/index.html @@ -0,0 +1,79 @@ +--- +title: Date.prototype.getHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/getHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getHours +--- +
{{JSRef}}
+ +

 

+ +

Il metodo  getHours() restituisce l'ora per la data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-gethours.html")}}
+ + + +

Sintassi

+ +
dateObj.getHours()
+ +

Valore di ritorno

+ +

Un numero di tipo integer, tra 0 e 23, rappresentante l'ora per la data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando getHours()

+ +

La seconda dichiarazione qui sotto assegna il valore 23 alla variabile hours, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var hours = Xmas95.getHours();
+
+console.log(hours); // 23
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.18', 'Date.prototype.getHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getHours")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html b/files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html new file mode 100644 index 0000000000..68825e21ca --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html @@ -0,0 +1,77 @@ +--- +title: Date.prototype.getMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getMilliseconds() restituisce i millisecondi nella data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getmilliseconds.html")}}
+ + + +

Sintassi

+ +
dateObj.getMilliseconds()
+ +

Valore di ritorno

+ +

Un numero, tra  0 e 999, rappresentante i millisecondi per la data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando  getMilliseconds()

+ +

Il seguente esempio assegna la porzione di millisecondi del tempo corrente alla variabile milliseconds:

+ +
var today = new Date();
+var milliseconds = today.getMilliseconds();
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.24', 'Date.prototype.getMilliseconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getMilliseconds")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getminutes/index.html b/files/it/web/javascript/reference/global_objects/date/getminutes/index.html new file mode 100644 index 0000000000..91f458cbda --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getminutes/index.html @@ -0,0 +1,77 @@ +--- +title: Date.prototype.getMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getMinutes() restituisce i minuti nella data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getminutes.html")}}
+ +

Sintassi

+ +
dateObj.getMinutes()
+ +

Valore di ritorno

+ +

Un numero di tipo integer, tra 0 e 59, rappresentante i minuti nella data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando getMinutes()

+ +

La seconda dichiarazione qui soto assegna il valore 15 alla variabile minutes, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var minutes = Xmas95.getMinutes();
+
+console.log(minutes); // 15
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.20', 'Date.prototype.getMinutes')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getMinutes")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getmonth/index.html b/files/it/web/javascript/reference/global_objects/date/getmonth/index.html new file mode 100644 index 0000000000..3d954b4ed5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getmonth/index.html @@ -0,0 +1,90 @@ +--- +title: Date.prototype.getMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMonth +--- +
{{JSRef}}
+ +

 

+ +

Il metodo  getMonth() restituisce il mese nella data specificata in accordo con l'ora locale, come un valore in base zero (dove zero indica il primo mese dell'anno).

+ +
{{EmbedInteractiveExample("pages/js/date-getmonth.html")}}
+ + + +

Sintassi

+ +
dateObj.getMonth()
+ +

Valore di ritorno

+ +

Un numero di tipo  integer, tra 0 e 11, rappresentante il mese nella data fornita in accordo con l'ora locale. 0 corrisponde a Gennaio, 1 a Febbraio , e cosi' via.

+ +

Esempi

+ +

Utilizzando getMonth()

+ +

La seconda dichiarazione qui sotto assegna il valore 11 alla variabile month, basata sul valore dell'oggetto {{jsxref("Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var month = Xmas95.getMonth();
+
+console.log(month); // 11
+
+ +
+

Note: Se necessitato , il nome completo di un mese ("January" per esempio ) può essere ottenuto utilizzando Intl.DateTimeFormat() con un prametro options .  Utilizzando questo metodo, l'internazionalizzazione risulta più semplice:

+ +
var options = { month: 'long'};
+console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95));
+// December
+console.log(new Intl.DateTimeFormat('de-DE', options).format(Xmas95));
+// Dezember
+
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.12', 'Date.prototype.getMonth')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getMonth")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getseconds/index.html b/files/it/web/javascript/reference/global_objects/date/getseconds/index.html new file mode 100644 index 0000000000..3faac2c56e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getseconds/index.html @@ -0,0 +1,79 @@ +--- +title: Date.prototype.getSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getSeconds() restituisce i secondi nella data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getseconds.html")}}
+ + + +

Sintassi

+ +
dateObj.getSeconds()
+ +

Valore di ritorno

+ +

Un numero di tipo integer, tra 0 e 59, rappresentante i secondi nella data fonita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando  getSeconds()

+ +

La seconda dichiarazione qui sotto assegna il valore  30 alla variabile seconds, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var seconds = Xmas95.getSeconds();
+
+console.log(seconds); // 30
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.22', 'Date.prototype.getSeconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getSeconds")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/gettime/index.html b/files/it/web/javascript/reference/global_objects/date/gettime/index.html new file mode 100644 index 0000000000..0424faa8a4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/gettime/index.html @@ -0,0 +1,125 @@ +--- +title: Date.prototype.getTime() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTime +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTime +--- +
 {{JSRef}}
+ +
 
+ +
Il metodo getTime() restituisce il numero di millisecondi a partire dalla Unix Epoch.
+ +

 

+ +

* JavaScript utilizza i millisecondi come unità di misura, mentre lo Unix Time è in secondi.

+ +

getTime() utilizza sempre lo UTC per la rappresentazione del  tempo. Ad esempio, un client browser in un fuso orario, getTime() sarà lo stesso come un client browser in qualsiasi altro fuso orario.

+ +

Puoi utilizzare questo metodo per aiutare ad assegnare una data ed un orario ad un altro oggetto {{jsxref("Date")}} . Questo metodo è funzionalmente equivalente al metodo {{jsxref("Date.valueof", "valueOf()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-gettime.html")}}
+ + + +

Sintassi

+ +
dateObj.getTime()
+ +

Valore di Ritorno

+ +

Un numero rappresentante i millisecondi trascorsi tra il  1 Gennaio 1970 00:00:00 UTC e la data utilizzata.

+ +

Esempi

+ +

Utilizzare getTime() per copiare le date

+ +

Costruire un oggetto data con lo stesso valore di tempo.

+ +
// Poichè il mese è in base zero, birthday sarà January 10, 1995
+var birthday = new Date(1994, 12, 10);
+var copy = new Date();
+copy.setTime(birthday.getTime());
+
+ +

Misurare il tempo di esecuzione

+ +

Sottrarre due susseguenti chiamate getTime() su nuovi oggetti {{jsxref("Date")}} generati, dà il lasso di tempo tra queste due chiamate. Ciò può essere usato per calcolare il tempo di esecuzione di alcune operazioni. Vedere anche {{jsxref("Date.now()")}} per prevenire la non necessaria instanziazione di oggetti {{jsxref("Date")}}.

+ +
var end, start;
+
+start = new Date();
+for (var i = 0; i < 1000; i++) {
+  Math.sqrt(i);
+}
+end = new Date();
+
+console.log('Operation took ' + (end.getTime() - start.getTime()) + ' msec');
+
+ +

Precisione di tempo ridotta

+ +

Per offrire protezione contro attacchi di tipo timing e fingerprinting, la precisione di new Date().getTime() potrebbe essere arrotondata a seconda dei settings del browser. In Firefox, la preferenza privacy.reduceTimerPrecision  è abilitata di default e predefinita a 20µs in Firefox 59; in 60 sarà  2ms.

+ +
// precisione di tempo ridotta (2ms) in Firefox 60
+new Date().getTime();
+// 1519211809934
+// 1519211810362
+// 1519211811670
+// ...
+
+
+// precisione di tempo ridotta con  `privacy.resistFingerprinting` abilitata
+new Date().getTime();
+// 1519129853500
+// 1519129858900
+// 1519129864400
+// ...
+
+ +

In Firefox, puoi anche abilitare privacy.resistFingerprinting, la precisione sarà 100ms oppure il valore di  privacy.resistFingerprinting.reduceTimerPrecision.microseconds, qualunque sia superiore.

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioneStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.9', 'Date.prototype.getTime')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}{{Spec2('ESDraft')}} 
+ +

 Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Date.getTime")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html b/files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html new file mode 100644 index 0000000000..0f583c099f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html @@ -0,0 +1,99 @@ +--- +title: Date.prototype.getTimezoneOffset() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getTimezoneOffset() restituisce la differenza di fuso orario, in minuti, da corrente locale (host system settings) a UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-gettimezoneoffset.html")}}
+ + + +

Sintassi

+ +
dateObj.getTimezoneOffset()
+ +

Valore di ritorno

+ +

Un numero rappresentante  l'offset del fuso orario, in minuti, dalla data basata sul current host system settings a UTC.

+ +

Descrizione

+ +

Il time-zone offset è la differenza, in minuti, dall'ora locale a UTC. Nota che questo significa che l'offset è positivo se l'ora locale è indietro allo UTC e negativo se è avanti. Per esempio, per il fuso orario UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), sarà restituito -600.

+ + + + + + + + + + + + + + + + +
Current LocaleUTC-8UTCUTC+3
Return Value4800-180
+ +

L'offset di fuso orario restituito è quello che si applica per la Data su cui è chiamato. Dove l'host system è configurato per l'ora legale, l'offset cambierà in base alla data e al tempo che la Data rappresenta e a cui si applica l'ora legale.

+ +

Esempi

+ +

Utilizzando getTimezoneOffset()

+ +
// Get current timezone offset for host device
+var x = new Date();
+var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
+// 1
+
+// Get timezone offset for International Labour Day (May 1) in 2016
+// Be careful, the Date() constructor uses 0-indexed month so May is
+// represented with 4 (and not 5)
+var labourDay = new Date(2016, 4, 1)
+var labourDayOffset = labourDay.getTimezoneOffset() / 60;
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.26', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getTimezoneOffset")}}

diff --git a/files/it/web/javascript/reference/global_objects/date/index.html b/files/it/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..1fc4c3d9d8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,249 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - Epoch + - JavaScript + - NeedsTranslation + - Time + - TopicStub + - Unix Epoch + - timeStamp +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Creates a JavaScript Date instance that represents a single moment in time in a platform-independent format. Date objects use a Unix Time Stamp, an integer value that is the number of milliseconds since 1 January 1970 UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-constructor.html")}}
+ + + +

Instantiating Date objects

+ +

The only way to create a new JavaScript Date object is to use the {{jsxref("new")}} operator:

+ +
let now = new Date();
+ +

If you simply call the {{jsxref("Date", "Date()")}} object directly, the returned value is a string instead of a Date object. There's no Date literal syntax in JavaScript.

+ +

Syntax

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
+
+ +

Parameters

+ +

There are four basic forms for the Date() constructor:

+ +

No parameters

+ +

When no parameters are provided, the newly-created Date object represents the current date and time, specified in the local time zone, as of the time of instantiation.

+ +

Unix timestamp

+ +
+
value
+
A Unix Time Stamp which is an integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the Unix epoch), with leap seconds ignored. Keep in mind that most Unix timestamp functions are only accurate to the nearest second.
+
+ +

Timestamp string

+ +
+
dateString
+
A string value representing a date, specified in a format recognized by the {{jsxref("Date.parse()")}} method (these formats are IETF-compliant RFC 2822 timestamps and also strings in a version of ISO8601). +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

+
+
+
+ +

Individual date and time component values

+ +

Given at least a year and month, this form of Date() returns a Date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (1 for the day and 0 for every other component).

+ +
+
year
+
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999; all other values are the actual year. See the {{anch("Two_digit_years_map_to_1900_-_1999", "example below")}}.
+
monthIndex
+
Integer value representing the month, beginning with 0 for January to 11 for December.
+
day {{optional_inline}}
+
Integer value representing the day of the month. If not specified, the default value of 1 is used.
+
hours {{optional_inline}}
+
Integer value representing the hour of the day. The default is 0 (midnight).
+
minutes {{optional_inline}}
+
Integer value representing the minute segment of a time. The default is 0 minutes past the hour.
+
seconds {{optional_inline}}
+
Integer value representing the second segment of a time. The default is zero seconds past the minute.
+
milliseconds {{optional_inline}}
+
Integer value representing the millisecond segment of a time. The default is 0 milliseconds past the second.
+
+ +

User notes

+ +

The Unix epoch and timestamps

+ +

A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time is called the Unix epoch, which is the predominant base value for computer-recorded date and time values.

+ +
+

Note: It's important to keep in mind that the date and time is stored in the local time zone, and that the basic methods to fetch the date and time or its components all work in the local time zone as well.

+
+ +

A day is made up of 86,400,000 milliseconds. Given that and the size of the underlying number used to record the timestamp, and it can be calculated that the Date object can represent dates within ±100,000,000 (one hundred million) days relative to January 1, 1970 UTC. That means that in the year 293,742, we'll have to think about fixing this.

+ +

Date format and time zone conversions

+ +

There are a number of methods available to obtain the date in various formats, as well as to do time zone conversions. Especially useful are the functions that output the date and time in Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. This time is historically known as Greenwich Mean Time, as UTC lies along the meridian that includes London and nearby Greenwhich in the United Kingdom. The user's device provides the local time.

+ +

In addition to methods to read and alter individual components of the local date and time, such as {{jsxref("Date.getDay", "getDay()")}} and {{jsxref("Date.setHours", "setHours()")}}, there are also versions of the same methods that read and maniuplate the date and time using UTC, such as {{jsxref("Date.getUTCDay()", "getUTCDay()")}} and {{jsxref("Date.setHoursUTC", "setUTCHours()")}}.

+ +

Properties

+ +
+
{{jsxref("Date.prototype")}}
+
Allows the addition of properties to a JavaScript Date object.
+
Date.length
+
The value of Date.length is 7. This is the number of arguments handled by the constructor. It's not generally a useful result.
+
+ +

Methods

+ +
+
{{jsxref("Date.now()")}}
+
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.
+
{{jsxref("Date.parse()")}}
+
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC, with leap seconds ignored. +
+

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

+
+
+
{{jsxref("Date.UTC()")}}
+
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.
+
+ +

JavaScript Date instances

+ +

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

+ +

Date.prototype Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
+ +

Examples

+ +

Several ways to create a Date object

+ +

The following examples show several ways to create JavaScript dates:

+ +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+ +
var today = new Date();
+var birthday = new Date('December 17, 1995 03:24:00');
+var birthday = new Date('1995-12-17T03:24:00');
+var birthday = new Date(1995, 11, 17);
+var birthday = new Date(1995, 11, 17, 3, 24, 0);
+
+ +

Two digit years map to 1900 - 1999

+ +

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// Deprecated method, 98 maps to 1998 here as well
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

Calculating elapsed time

+ +

The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.

+ +

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

+ +
// using Date objects
+var start = Date.now();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = Date.now();
+var elapsed = end - start; // elapsed time in milliseconds
+
+ +
// using built-in methods
+var start = new Date();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = new Date();
+var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
+
+ +
// to test a function and get back its return
+function printElapsedTime(fTest) {
+  var nStartTime = Date.now(),
+      vReturn = fTest(),
+      nEndTime = Date.now();
+
+  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
+  return vReturn;
+}
+
+var yourFunctionReturn = printElapsedTime(yourFunction);
+
+ +
+

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

+
+ +

Get the number of seconds since Unix Epoch

+ +
var seconds = Math.floor(Date.now() / 1000);
+
+ +

In this case it's important to return only an integer (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses {{jsxref("Math.floor()")}} and not {{jsxref("Math.round()")}}).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date", 3)}}

diff --git a/files/it/web/javascript/reference/global_objects/date/now/index.html b/files/it/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..dcf3650fd0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,96 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

Il metodo Date.now() restituisce il numero di millisecondi trascori dal Gennaio 1, 1970 00:00:00 UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-now.html")}}
+ +

Sintassi

+ +
var timeInMs = Date.now();
+ +

Valore di ritorno

+ +

Un {{jsxref("Number")}} rappresentante i millisecondi trascorsi fin dall'epoca UNIX.

+ +

Descrizione

+ +

Poichè now() è un metodo statico di  {{jsxref("Date")}}, lo utilizzerai sempre come Date.now().

+ +

Pecisione di tempo ridotta

+ +

Per offrire protezione contro attacchi di tipo timing e fingerprinting, la precisione di  Date.now() potrebbe essere arrotondata  a seconda dei settings del browser.
+ In Firefox,  la preferenza di  privacy.reduceTimerPrecision  è abilitata di default e predefinita a 20ms in Firefox 59; in 60 sarà 2ms.

+ +
// precisione di tempo ridotta (2ms) in Firefox 60
+Date.now()
+// 1519211809934
+// 1519211810362
+// 1519211811670
+// ...
+
+
+//  precisione di tempo ridotta con `privacy.resistFingerprinting` abilitata
+Date.now();
+// 1519129853500
+// 1519129858900
+// 1519129864400
+// ...
+
+ +

In Firefox, puoi anche abiliytare privacy.resistFingerprinting, la precisione sarà 100ms oppure il valore di privacy.resistFingerprinting.reduceTimerPrecision.microseconds, qualunque sia più grande.

+ +

Polyfill

+ +

Tale metodo è stato standardizzato in ECMA-262 5th edition. Motori che non sono stati aggiornati al supporto di questo metodo possono ovviare alla sua assenza utilizzando il seguente shim:

+ +
if (!Date.now) {
+  Date.now = function now() {
+    return new Date().getTime();
+  };
+}
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementata in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ + + +

{{Compat("javascript.builtins.Date.now")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/utc/index.html b/files/it/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..cfbf1abb10 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,135 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +
{{JSRef}}
+ +

Il metodo Date.UTC() accetta gli stessi parametri del costruttore {{jsxref("Date")}}, ma li tratta come UTC. Restituisce  il numero di millisecondi fin dal Gennaio 1, 1970, 00:00:00 UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-utc.html")}}
+ + + +

Sintassi

+ +

ECMAScript 2017 e successivi:

+ +
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])
+ +

ECMAScript 2016 e anteriori: (utilizzo di month richiesto)

+ +
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
+ +

Parametri

+ +
+
year
+
Un anno intero.
+
month
+
Un integer tra 0 (Gennaio) e 11 (Dicembre) rappresentante il mese. (Fino a ECMAScript 2016, month era un parametro richiesto. Con ES2017, non lo è più.)
+
day {{optional_inline}}
+
Opzionalel. Un integer tra 1 e 31 rappresentante il giorno del mese. Se omesso, è predefinito a 1.
+
hour {{optional_inline}}
+
Un integer tra  0 e 23 rappresentante le ore. Se omesso è predefinito a 0.
+
minute {{optional_inline}}
+
Un  integer tra 0 e 59 rappresentante i minuti.  Se omesso, è predefinito a 0.
+
second {{optional_inline}}
+
Un integer tra  0 e 59 rappresentante i secondi. Se omesso, è predefinito a 0.
+
millisecond {{optional_inline}}
+
Un  integer tra 0 e 999 rappresentante i millisecondi. Se omesso, è predefinito a 0.
+
+ +

Valore di ritorno

+ +

Un numero rappresentante i umeri di millisecondi per la data fornita sin dal Gennaio 1, 1970, 00:00:00, UTC.

+ +

Descrizione

+ +

UTC() prende date delimitate da virgola e parametri tempo e restituisce il numero di millisecondi tra Gennaio 1, 1970, 00:00:00, tempo universale ed il tempo e la data specificata.

+ +

Gli anni tra 0 e 99 sono convertiti ad un anno nel 20mo secolo(1900 + year); per esempio, 95 è convertito  all'anno 1995.

+ +

Il metodo UTC() differisce dal costruttore {{jsxref("Date")}} in due modi.

+ + + +

Se un parametro è fuori dal range previsto, il metodo UTC() aggiorna gli altri parametri per adattare il valore. Per esempio, se 15 è usato per il mese, l'anno sarà incrementato di 1 (year + 1) e 3 sarà usato per il mese.

+ +

UTC() è un metodo statico di {{jsxref("Date")}}, per questo è chiamato come Date.UTC() invece che come un metodo di istanza {{jsxref("Date")}}.

+ +

Esempi

+ +

Utilizzando Date.UTC()

+ +

La seguente dichiarazione crea un oggetto {{jsxref("Date")}} con gli argomenti trattati come  UTC invece di local:

+ +
var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}} Definizione iniziale. Implementata in JavaScript 1.0.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.UTC")}}

+ +

Note di compatibilità

+ +

Date.UTC con meno di due argomenti

+ +

Quando si provvedono meno di due argomenti a Date.UTC, ECMAScript 2017 richiede che  {{jsxref("NaN")}} sia restituito. Motori che non supportavano tale comportamento sono stati aggiornati (vedere {{bug(1050755)}}, ecma-262 #642).

+ +
Date.UTC();
+Date.UTC(1);
+
+// Safari: NaN
+// Chrome/Opera/V8: NaN
+
+// Firefox <54: non-NaN
+// Firefox 54+: NaN
+
+// IE: non-NaN
+// Edge: NaN
+
+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/decodeuri/index.html b/files/it/web/javascript/reference/global_objects/decodeuri/index.html new file mode 100644 index 0000000000..40a65b0c57 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/decodeuri/index.html @@ -0,0 +1,120 @@ +--- +title: decodeURI() +slug: Web/JavaScript/Reference/Global_Objects/decodeURI +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURI +--- +
{{jsSidebar("Objects")}}
+ +

Sommario

+ +

La funzione decodeURI() decodifica un {{Glossary("URI")}} creato da {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} o una funzione simile.

+ +

Sintassi

+ +
decodeURI(encodedURI)
+ +

Parametri

+ +
+
encodedURI
+
Un {{Glossary("URI")}} completo.
+
+ +

Descrizione

+ +

Sostituisce ogni sequenza di escape nell'{{Glossary("URI")}} codificato con il carattere che la rappresenta, ma non decodifica sequenze di escape che non potrebbero essere state create dalla {{jsxref("Global_Objects/encodeURI", "encodeURI()")}}, come il carattere #.

+ +

Esempi

+ +

Decodificare un URL in Cirillico

+ +
decodeURI("https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
+// "https://developer.mozilla.org/ru/docs/JavaScript_шеллы"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.1', 'decodeURI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-decodeuri-encodeduri', 'decodeURI')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html b/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html new file mode 100644 index 0000000000..243bd14a93 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html @@ -0,0 +1,124 @@ +--- +title: decodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione decodeURIComponent() decodifica una parte di {{Glossary("URI")}} creata da {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}} o una funzione simile.

+ +

Sintassi

+ +
decodeURIComponent(encodedURIComponent)
+ +

Parametri

+ +
+
encodedURIComponent
+
Una parte codificata di un {{Glossary("URI")}}
+
+ +

Descrizione

+ +

Sostituisce ogni sequenza di escape nella parte di {{Glossary("URI")}} codificata con il carattere che la rappresenta.

+ +

Esempio

+ +

Decodificare una parte di URL in Cirillico

+ +
decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
+// "JavaScript_шеллы"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.2', 'decodeURIComponent')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-decodeuricomponent-encodeduricomponent', 'decodeURIComponent')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/encodeuri/index.html b/files/it/web/javascript/reference/global_objects/encodeuri/index.html new file mode 100644 index 0000000000..24118aec60 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/encodeuri/index.html @@ -0,0 +1,160 @@ +--- +title: encodeURI() +slug: Web/JavaScript/Reference/Global_Objects/encodeURI +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione encodeURI() codifica un {{Glossary("URI")}} sostituendo alcuni specifici caratteri con una, due, tre o quattro sequenze di escape, che rappresentano il carattere codificato in {{Glossary("UTF-8")}} (le sequenze di quattro caratteri di escape verrano solo create per i caratteri composti da due caratteri "surrogati").

+ +

Sintassi

+ +
encodeURI(uri)
+ +

Parametri

+ +
+
uri
+
Un {{Glossary("URI")}} completo.
+
+ +

Descrizione

+ +

Questa funzione assume che uri sia un {{Glossary("URI")}} completo, quindi non codifica i caratteri riservati che hanno un significato particolare nell'{{Glossary("URI")}}.

+ +

encodeURI sostituisce tutti i caratteri con la sequenza di escape UTF-8 appropriata, ecceto i seguenti:

+ + + + + + + + + + + + + + + + + + + + +
TipoCaratteri
Caratteri riservati; , / ? : @ & = + $
Caratteri non codificatilettere, cifre, - _ . ! ~ * ' ( )
Score#
+ +

encodeURI non prepara una richiesta HTTP GET o POST, ad esempio per {{domxref("XMLHttpRequest")}}, perché "&", "+" e "=" non vengono codificati, ma sono trattati come caratteri speciali nelle richieste GET e POST. Se è necessario codificarli, usare la funzione {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}.

+ +

Se si tenta di codificare un surrogato che non è parte di una coppia, verrà generato un {{jsxref("Global_Objects/URIError", "URIError")}}.

+ +
// Coppia surrogata: Ok
+encodeURI("\uD800\uDFFF");
+
+// Solo il primo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURI("\uD800");
+
+// Solo il secondo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURI("\uDFFF"); 
+ +

Se uno desidera seguire il più recente standard per gli {{Glossary("URL")}} RFC3986, nel quale le parentesi quadre sono caratteri riservati (per gli indirizzi {{Glossary("IPv6")}}), può essere utile il seguente codice:

+ +
function fixedEncodeURI(str) {
+    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
+}
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.3', 'encodeURI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-encodeuri-uri', 'encodeURI')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html new file mode 100644 index 0000000000..66b290ccb4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html @@ -0,0 +1,162 @@ +--- +title: encodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +--- +
{{jsSidebar("Objects")}}
+ +

Sommario

+ +

La funzione encodeURIComponent() codifica un componente di un {{Glossary("URI")}} sostituendo alcuni specifici caratteri con una, due, tre o quattro sequenze di escape, che rappresentano il carattere codificato in {{Glossary("UTF-8")}} (le sequenze di quattro caratteri di escape verrano solo create per i caratteri composti da due caratteri "surrogati").

+ +

Sintassi

+ +
encodeURIComponent(uriComponent);
+ +

Parametri

+ +
+
uriComponent
+
Una parte di un {{Glossary("URI")}}
+
+ +

Descrizione

+ +

encodeURIComponent sostituisce tutti i caratteri esclusi i seguenti: lettere, cifre, - _ . ! ~ * ' ( )

+ +

Se si tenta di codificare un surrogato che non è parte di una coppia, verrà generato un {{jsxref("Global_Objects/URIError", "URIError")}}.

+ +
// Coppia surrogata: Ok
+encodeURIComponent("\uD800\uDFFF");
+
+// Solo il primo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURIComponent("\uD800");
+
+// Solo il secondo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURIComponent("\uDFFF");
+ +

Per evitare problemi inaspettati durante le richieste al server, bisognerebbe richiamare encodeURIComponent su ogni dato inserito dall'utente che verrà passato come parte di un {{Glossary("URI")}}. Per esempio, un un utente potrebbe digitare "Cani&Gatti = animali". Senza utilizzare la funzione encodeURIComponent, la richiesta verrebbe costruita in modo simile a "commento=Cani&Gatti%20=%20animali". Notare che sono due variabili separate: "commento" e "Gatti%20". Utilizzando quuesta funzione verrebbe invece costruita come "commento=Cani%26Gatti%20%3D%20animali​".

+ +

Utilizzando application/x-www-form-urlencoded, gli spazi devono essere sostituiti da un "+"., quindi si potrebbe usare la funzione encodeURIComponent seguita da un altra sostituzione da "%20" a "+".

+ +

Per aderire con più precisione allo standard RFC 3986 (secondo il quale !'() e * sono caratteri riservati), si può usare la seguente funzione:

+ +
function fixedEncodeURIComponent(str) {
+  return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
+    return '%' + c.charCodeAt(0).toString(16);
+  });
+}
+
+ +

Esempi

+ +

Il seguente esempio fornisce un metodo per codificare come richiesto dall'header Content-Disposition:

+ +
var fileName = 'my file(2).txt';
+var header = "Content-Disposition: attachment; filename*=UTF-8''"
+             + encodeRFC5987ValueChars(fileName);
+
+console.log(header);
+// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
+
+
+function encodeRFC5987ValueChars (str) {
+    return encodeURIComponent(str).
+        // Notare che anche se per l'RFC3986 "!" è riservato, non lo è per
+        // l' RFC5987, quindi non viene sostituito
+        replace(/['()]/g, escape). // i.e., %27 %28 %29
+        replace(/\*/g, '%2A').
+            // Per l'RFC5987 questi caratteri non necessitano di essere codificati,
+            // quindi possiamo consentire un po' più di leggibilità: |`^
+            replace(/%(?:7C|60|5E)/g, unescape);
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/escape/index.html b/files/it/web/javascript/reference/global_objects/escape/index.html new file mode 100644 index 0000000000..77fa1e5bf0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/escape/index.html @@ -0,0 +1,126 @@ +--- +title: escape() +slug: Web/JavaScript/Reference/Global_Objects/escape +translation_of: Web/JavaScript/Reference/Global_Objects/escape +--- +
+
+
{{jsSidebar("Objects")}} {{deprecated_header}}
+
+
+ +

Sommario

+ +

La funzione escape(), deprecata, crea una nuova stringa nella quale alcuni caratteri vengono sostituiti con una sequenza di escape esadecimale. È preferibile usare le funzioni {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} o {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}.

+ +

Sintassi

+ +
escape(string)
+ +

Parametri

+ +
+
string
+
La stringa da codificare.
+
+ +

Descrizione

+ +

La funzione escape() è una proprietà dell'oggetto globale. Vengono codificati tutti i caratteri speciali, ad eccezione di: @ * _ + - . /

+ +

I caratteri vengono sostituiti con codici esadecimali che possono avere due caratteri, se il loro valore è minore o ugugale a 0xFF, (%xx) oppure quattro (%uxxxx).

+ +

Esempi

+ +
escape("abc123");     // "abc123"
+escape("äöü");        // "%E4%F6%FC"
+escape("ć");          // "%u0107"
+
+// Caratteri speciali
+escape("@*_+-./");    // "@*_+-./"
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-B.2.1', 'escape')}}{{Spec2('ES5.1')}}Definita nell'appendice B, "Compatibility"
{{SpecName('ES6', '#sec-escape-string', 'escape')}}{{Spec2('ES6')}}Definita nell'appendice B, "Additional ECMAScript Features for Web Browsers"
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/eval/index.html b/files/it/web/javascript/reference/global_objects/eval/index.html new file mode 100644 index 0000000000..22e3c70bb6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/eval/index.html @@ -0,0 +1,231 @@ +--- +title: eval() +slug: Web/JavaScript/Reference/Global_Objects/eval +translation_of: Web/JavaScript/Reference/Global_Objects/eval +--- +

{{jsSidebar("Objects")}}

+ +

Riassunto

+ +

Il metodo eval() esegue il codice JavaScript rappresentato come una stringa.

+ +

Sintassi

+ +
eval(stringa)
+ +

Parametri

+ +
+
string
+
Una stringa che rappresenta un'espressione JavaScript, dichiarazione o sequenza di istruzioni. L'espressione può includere le variabili e le proprietà degli oggetti esistenti.
+
+ +

Descrizione

+ +

eval() è una funzione dell'oggetto globale.

+ +

L'argomento della funzione eval() è una stringa. Se la stringa rappresenta un'espressione, eval() esegue l'espressione. Se l'argomento rappresenta una o più dichiarazioni Javascript, eval()esegue le dichiarazioni. Non chiamare eval() per eseguire un'operazione aritmetica, JavaScript la esegue automaticamente.

+ +

Se si costruisce un'espressione aritmetica come una stringa, è possibile usare eval() per eseguirla in un secondo momento. Ad esempio, supponiamo di avere una variabile x. E' possibile rinviare il valore di un'espressione che coinvolge x  assegnando il valore della stringa dell'espressione, tipo "3 * x + 2", ad una variabile, e quindi chiamare eval() in un punto successivo dello script.

+ +

Se l'argomento di eval() non è una stringa, eval() restituisce l'argomento immutato. Nell'esempio qui sotto, il costrutto String viene specificato, e eval() ritorna un oggetto String piuttosto che il risultato della stringa.

+ +
eval(new String("2 + 2")); // returns a String object containing "2 + 2"
+eval("2 + 2");             // returns 4
+
+ +

E' possibile aggirare questa limitazione in modo generico utilizzando toString().

+ +
var expression = new String("2 + 2");
+eval(expression.toString());
+
+ +

Non è possibile utilizzare la funzione eval indirettamente, invocandola con un nome diverso da eval(); se lo fai , potrebbe verificarsi un errore di sintassi. Per esempio, non si dovrebbe usare il seguente codice:

+ +
var x = 2;
+var y = 4;
+var myEval = eval;
+myEval("x + y");
+
+ +

Non usate eval inutilmente!

+ +

eval()è una funzione pericolosa, che esegue il codice con i privilegi dell'amministratore della pagina. Se si esegue eval() con una stringa che potrebbe essere interessata da un malintenzionato, si può interrompere l'esecuzione del codice dannoso sul computer dell'utente con il permesso della pagina Web. Ancora più importante, codici di terze parti possono vedere come eval() è stata invocata, che può portare a possibili attacchi come {{jsxref("Global_Objects/Function", "Function")}}.

+ +

eval() è generalmente più lenta rispetto alle alternative, dal momento che deve chiamare l'interprete di JS, mentre moltri altri costrutti sono ottimizzati da moderni "motori" JS.

+ +

Queste sono alternative più sicure (e veloci! ) ad eval() per comuni impieghi.

+ +

Accesso alle proprietà utente

+ +

Si consiglia si non utilizzare eval() per conventire i nomi di proprietà in proprietà. Consideriamo l'esempio qui sotto, dove le proprietà dell'oggetto acui accedere non è nota fino a quando viene eseguito il codice. Questo può essere fatto con eval:

+ +
var obj = { a: 20, b: 30 };
+var propname = getPropName();  //returns "a" or "b"
+
+eval( "var result = obj." + propname );
+
+ +

Tuttavia, eval () non è necessario qui. In realtà, il suo uso è sconsigliato qui. Invece, utilizzare gli operatori membri, che sono molto più veloci e sicuri:

+ +
var obj = { a: 20, b: 30 };
+var propname = getPropName();  //returns "a" or "b"
+var result = obj[ propname ];  //  obj[ "a" ] is the same as obj.a
+
+ +

Utilizzare le funzioni invece di eseguire frammenti di codice

+ +

JavaScript ha funzioni di prima classe, il che significa che è possibile passare funzioni come argomenti ad altre API, memorizzarli in variabili e le proprietà degli oggetti, e così via. Molte API DOM sono progettate con questo in mente, in modo da poter (e devono) scrivere a:

+ +
// instead of setTimeout(" ... ", 1000) use:
+setTimeout(function() { ... }, 1000);
+
+// instead of elt.setAttribute("onclick", "...") use:
+elt.addEventListener("click", function() { ... } , false); 
+ +

Le chiusure sono utili anche come un modo per creare funzioni parametrizzate senza concatenazioni di stringhe.

+ +

Analisi di JSON (conversione di stringhe in oggetti JavaScript)

+ +

Se la stringa che si sta chiamando eval() contiene dati (per esempio un array: "[1, 2, 3]"), al ontrario del codice, si dovrebbe considerareil passaggio a JSON, che permette la stringa di utilizzre un sottoinsieme della sintassi Javascript per rappresentare i dati. Vedi anche Downloading JSON and JavaScript in extensions.

+ +

Notare che, poichè la sintassi JSON è limitata rispetto alla sintassi di Javascript, molti letterali Javascript validi non analizzare come JSON. Ad esempio, le virgole finali non sono ammessi in JSON, e nomi di proprietà (chiavi) in letterali oggetto devono essere racchiusi tra virgolette. Assicurarsi di utilizzare un serializzatore JSON per generare le stringhe che vrranno successivamente analizzate come JSON.

+ +

Paasare i dati al posto di codici

+ +

Ad esempio, un'estensione progettata per raschiare contenuti delle pagine Web potrebbe avere le regole di raschiatura definite in  XPath invece di codice Javascript.

+ +

Eseguire codice con privilegi limitati

+ +

Se devi eseguire il codice, considerare di eseguirlo con privilegi ridotti. Questo consilio vale soprattutto per le estensioni e le applicazioni XUL, che possono utilizzare  Components.utils.evalInSandbox per questo.

+ +

Esempio

+ +

Il seguente esempio mostra output utilizzando document.write. Nel server-side JavaScript, è possibile visualizzare la stessa uscita chiamando la funzione write() invece di utilizzare il document.write().

+ +

Esempio: Usare eval

+ +

Nel codice seguente, entrambe le dichiarazioni contenenti  eval() restituiscono 42. La prima restituisce la stringa  "x + y + 1" ; la seconda esegue la stringa "42".

+ +
var x = 2;
+var y = 39;
+var z = "42";
+eval("x + y + 1"); // returns 42
+eval(z);           // returns 42
+
+ +

Esempio: Usare eval Per eseguire una serie di istruzioni JavaScript.

+ +

Il seguente esempio utilizza  eval() per eseguire la stringa str. Questa stringa consiste in una serie di istruzioni JavaScript che aprono una finestra di avviso e assegnano a z un valore 42 se x è di cinque, e assegna 0 a z altrimenti. Quando viene eseguita la seconda istruzione, eval() farà si che questa dichiarazioni da effettuare, e sarà anche eseguire l'insieme di istruzioni e restituire il valore che viene assegnato a z.

+ +
var x = 5;
+var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; ";
+
+document.write("<P>z is ", eval(str));
+ +

Esempio: L'ultima espressione viene eseguita

+ +

eval()restituisce il valore dell'ultima espressione valutata.

+ +
var str = "if ( a ) { 1+1; } else { 1+2; }";
+var a = true;
+var b = eval(str);  // returns 2
+
+alert("b is : " + b);
+
+a = false;
+b = eval(str);  // returns 3
+
+alert("b is : " + b);
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.1.2.1', 'eval')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-eval-x', 'eval')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome per AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Gecko-specific notes

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/apply/index.html b/files/it/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..1c0d04272d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,250 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +tags: + - JavaScript + - funzione + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
+

{{JSRef}}

+ +

Il metodo apply() chiama una funzione passandole il "this" ed i parametri forniti sottoforma di array (o array-like object).

+ +

Nota: Mentre la sintassi di questa funzione è quasi completamente identica a quella di {{jsxref("Function.call", "call()")}}, la fondamentale differenza è che call() accetta una lista di parametri, mentre apply() accetta un singolo array contenente una lista di parametri.

+ +

Sintassi

+ +
fun.apply(thisArg, [argsArray])
+ +

Parametri

+ +
+
thisArg
+
Il valore del this da fornire alla chiamata a fun. Nota che questo potrebbe non essere l'effettivo valore visto dal metodo: se il metodo non è eseguito in {{jsxref("Strict_mode", "strict mode", "", 1)}}, {{jsxref("null")}} ed {{jsxref("undefined")}} saranno rimpiazzati dall'oggetto globale.
+
argsArray
+
Un array-like object che specifica i parametri con la quale la funzione fun deve essere chiamata. Può essere anche {{jsxref("null")}} o {{jsxref("undefined")}} nel caso nessun parametro dovesse essere passato. A partire da ECMAScript 5 questi parametri possono essere un qualunque array-like object invece di un semplice array. Vedi sotto per le {{anch("Browser_compatibility", "compatibilità nei browser")}}.
+
+ +

Descrizione

+ +

this solitamente si riferisce all'oggetto corrente, ma grazie ad apply è possibile scrivere un metodo una sola volta e riusarlo più volte su oggetti differenti passando ad apply, appunto, un this differente. Cosi viene eliminata la necessità di riscrivere di nuovo lo stesso metodo per un oggetto diverso.

+ +

apply è molto simile a {{jsxref("Function.call", "call()")}}, eccezion fatta per il modo in cui i parametri vengono passati. Puoi utilizzare un array di parametri invece della solita lista. Con apply, ad esempio, puoi utilizzare il seguente array literal: fun.apply(this, ['eat', 'bananas']), o il seguente oggetto {{jsxref("Array")}}: fun.apply(this, new Array('eat', 'bananas')).

+ +

Puoi anche utilizzare {{jsxref("Functions/arguments", "arguments")}} per il parametro argsArrayarguments è una variabile locale di tutte le funzioni. Può essere utilizzata per tutti i parametri non specificati dell'oggetto chiamato. In più, non è necessario che si conoscano i parametri dell'oggetto chiamato quando si utilizza apply.

+ +

Da ECMAScript 5 puoi anche usare qualunque tipo di array-like object. Ad esempio puoi utilizzare un {{domxref("NodeList")}} o un oggetto come { 'length': 2, '0': 'eat', '1': 'bananas' }.

+ +

{{note("La maggior parte dei browser, incluso Chrome 14 ed Internet Explorer 9, non accetto array-like objects e lanceranno una eccezione.")}}

+ +

Esempi

+ +

Utilizzare apply per concatenare costruttori

+ +

Puoi utilizzare apply per concatenare {{jsxref("Operators/new", "costruttori", "", 1)}} per un oggetto, in maniera simile a Java. Nel seguente esempio creeremo una {{jsxref("Function")}} globale chiamata construct, che ti permetterà di utilizzare un array-like object con un costruttore anziché una lista di argomenti.

+ +
Function.prototype.construct = function (aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +

Note: Il metodo Object.create() usato nell'esempio sovrastante è relativamente nuovo. Per un alternativa che utilizza le closures considera questo pezzo di codice:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+ +

Esempio d'uso:

+ +
function MyConstructor() {
+  for (var nProp = 0; nProp < arguments.length; nProp++) {
+    this['property' + nProp] = arguments[nProp];
+  }
+}
+
+var myArray = [4, 'Hello world!', false];
+var myInstance = MyConstructor.construct(myArray);
+
+console.log(myInstance.property1);                // logs 'Hello world!'
+console.log(myInstance instanceof MyConstructor); // logs 'true'
+console.log(myInstance.constructor);              // logs 'MyConstructor'
+
+ +

Note: Il metodo non nativo Function.construct non funzionerà con alcuni costruttori nativi (come {{jsxref("Date")}}). In questi casi devi usare {{jsxref("Function.prototype.bind")}}. Immagina ad esempio di avere un array come il seguente da utilizzare con il costruttore {{jsxref("Global_Objects/Date", "Date")}}: [2012, 11, 4]; In questo caso dovresti scrivere qualcosa come: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))() — ad ogni modo questo non è il miglior modo di fare le cose e non andrebbe mai usato in produzione.

+ +

Utilizzare apply combinato alle funzioni built-in

+ +

Un intelligente uso di apply ti permette di utilizzare delle funzioni built-in per dei compiti che altrimenti sarebbero stati fatti, nel caso sottostante, ciclando l'array e scorrendo ogni suo elemento e sottoponendolo a dei controlli. L'esempio seguente dimostra come trovare il massimo / minimo valore all'interno di un array utilizzando Math.max/Math.min.

+ +
// min/max number in an array
+var numbers = [5, 6, 2, 3, 7];
+
+// using Math.min/Math.max apply
+var max = Math.max.apply(null, numbers);
+// This about equal to Math.max(numbers[0], ...)
+// or Math.max(5, 6, ...)
+
+var min = Math.min.apply(null, numbers);
+
+// vs. simple loop based algorithm
+max = -Infinity, min = +Infinity;
+
+for (var i = 0; i < numbers.length; i++) {
+  if (numbers[i] > max) {
+    max = numbers[i];
+  }
+  if (numbers[i] < min) {
+    min = numbers[i];
+  }
+}
+
+ +

Ma tieni a mente che nell'usare apply in questo modo si corre il rischio di superare il limite imposto dal motore JavaScript degli argomenti che possono essere passati ad una funzione.
+ Le conseguenze nel fare ciò variano da motore a motore (ad esempio JavaScriptCore ha il limite settato a mano di 65536 parametri), perché il limite non è specificato. Alcuni motori lanceranno una eccezione. Altri invece limiteranno arbitrariamente il numero dei parametri passati alla funzione su cui viene usato il metodo apply(). (Un esempio di quest'ultimo caso potrebbe essere quello di un motore che ha questo limite settato a 4 e, nell'esempio sovrastante, gli unici parametri che effettivamente saranno passati alla funzione saranno 5, 6, 2, 3, piuttosto che l'intero array.) Una decisione saggia, nel caso si prevede la possibilità di raggiungere un enorme numero di parametri, sarebbe quella di parzializzare il numero di parametri per lotti:

+ +
function minOfArray(arr) {
+  var min = Infinity;
+  var QUANTUM = 32768;
+
+  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
+    var submin = Math.min.apply(null, arr.slice(i, Math.min(i+QUANTUM, len)));
+    min = Math.min(submin, min);
+  }
+
+  return min;
+}
+
+var min = minOfArray([5, 6, 2, 3, 7]);
+
+ +

Usare apply come "monkey-patch"

+ +

L'attività del "monkey-patching" consiste nel modificare il funzionamento di un metodo senza dover andare a mettere mano al codice sorgente (cosa da evitare sempre e comunque). Difatti Apply può rivelarsi il modo migliore di modificare il funzionamento, ad esempio, di una funzione interna a Firefox o di una qualunque altra libreria JS. Data una funzione someobject.foo, è possibile modificarne il funzionamento in questo modo:

+ +
var originalfoo = someobject.foo;
+someobject.foo = function() {
+  // Do stuff before calling function
+  console.log(arguments);
+  // Call the function as it would have been called normally:
+  originalfoo.apply(this, arguments);
+  // Run stuff after, here.
+}
+
+ +

Questo metodo ritorna particolarmente utile quando vuoi debuggare eventi e interfacce con qualcosa che non espone API come i diversi eventi .on([event]... (usabili anche dal Devtools Inspector).

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale. Implementato in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

Vedi anche

+ + +
diff --git a/files/it/web/javascript/reference/global_objects/function/arguments/index.html b/files/it/web/javascript/reference/global_objects/function/arguments/index.html new file mode 100644 index 0000000000..949e5f9cdb --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,92 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Reference/Global_Objects/Function/arguments +tags: + - Deprecated + - Function + - JavaScript + - Property + - arguments +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +
{{JSRef}} {{deprecated_header}}
+ +

La proprieta' function.arguments fa riferimento ad un oggetto simile ad un array corrispondente ai parametri passati ad una funzione. Usa questa semplice variabile {{jsxref("Functions/arguments", "arguments")}} invece. Questa proprieta' non e' disponibile in strict mode.

+ +

Descrizione

+ +

La sintassi function.arguments e' deprecata. Il metodo consigliato per accedere all'oggetto {{jsxref("Functions/arguments", "arguments")}}, disponibile all'interno delle funzioni e' semplicemente mediante l'utilizzo di {{jsxref("Functions/arguments", "arguments")}}.

+ +

In caso di ricorsione, per esempio, se la funzione f e' presente diverse volte nello stack, il valore di f.arguments rappresenta i parametri corrispondenti alla chiamata alla funzione piu' recente.

+ +

Il valore della proprieta' arguments e' normalmente null se non c'e' una sua chiamata durante l'esecuzione della funzione (ovvero quando la funzione e' stata chiamata ma non ha ancora ritornato nessun valore).

+ +

Esempi

+ +
function f(n) { g(n - 1) }
+
+function g(n) {
+  console.log('before: ' + g.arguments[0])
+  if (n > 0) { f(n) }
+  console.log('after: ' + g.arguments[0])
+}
+
+f(2)
+
+console.log('returned: ' + g.arguments)
+
+// Output
+
+// before: 1
+// before: 0
+// after: 0
+// after: 1
+// returned: null
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0. Deprecated in favor of {{jsxref("Functions/arguments", "arguments")}} in ES3.
{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}{{Spec2('ES5.1')}}{{jsxref("Functions/arguments", "arguments")}} object
{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}{{Spec2('ES6')}}{{jsxref("Functions/arguments", "arguments")}} object
{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}{{Spec2('ESDraft')}}{{jsxref("Functions/arguments", "arguments")}} object
+ +

Compatibilita' Browser

+ +
+ + +

{{Compat("javascript.builtins.Function.arguments")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/arity/index.html b/files/it/web/javascript/reference/global_objects/function/arity/index.html new file mode 100644 index 0000000000..fec2d9e988 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/arity/index.html @@ -0,0 +1,26 @@ +--- +title: Function.arity +slug: Web/JavaScript/Reference/Global_Objects/Function/arity +translation_of: Archive/Web/JavaScript/Function.arity +--- +

{{JSRef}}{{Obsolete_Header}}

+ +
+

La proprieta' arity ritornava il numero di parametri richiesta da una funzione. Ad ogni modo non esiste piu' ed e' stata rimpiazzata dalla proprieta' {{JSxRef("Function.prototype.length")}}.

+
+ +

Specifiche

+ +

Implementato in JavaScript 1.2. Deprecato in JavaScript 1.4.

+ +

Compatibilita' Browser

+ + + +

{{Compat("javascript.builtins.Function.arity")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/bind/index.html b/files/it/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..38187ac5e6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,277 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +
{{JSRef}}
+ +

Il metodo bind() crea una nuova funzione che, quando chiamata, ha parola chiave this impostata sul valore fornito, con una data sequenza di argomenti che precede quella fornita quando viene chiamata la nuova funzione

+ +

{{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}}

+ + + +

Sintassi

+ +
function.bind(thisArg[, arg1[, arg2[, ...]]])
+ +

Parametri

+ +
+
thisArg
+
Il valore va passato come parametro alla funzione target quando viene chiamata la funzione associata. Il valore viene ignorato se la funzione associata viene costruita utilizzando l'operatore {{jsxref("Operators/new", "new")}}. Quando si utilizza bind per creare una funzione (fornita come callback) all'interno di un setTimeout, qualsiasi valore primitivo passato come thisArg viene convertito in oggetto. Se non vengono forniti argomenti per vincolarlo, l'esecuzione viene considerata come thisArg per la nuova funzione.
+
arg1, arg2, ...
+
Argomenti da anteporre agli argomenti forniti alla funzione associata quando si richiama la funzione di destinazione.
+
+ +

Valore restituito

+ +

Una copia della funzione data con specificato this valore e gli argomenti iniziali.

+ +

Descrizione

+ +

La funzione bind() crea una nuova funzione associata (BF, bound function). Un BF è un exotic function object (oggetto funzione esotico, un termine di ECMAScript 2015) che racchiude l'oggetto funzione originale. Chiamare un BF generalmente comporta l'esecuzione della sua funzione wrapped (avvolta).
+ Un BF ha le seguenti proprietà interne:

+ + + +

Quando viene chiamata la funzione associata, chiama il metodo interno [[Call]] su [[BoundTargetFunction]], con i seguenti argomenti call(boundThis, ...args). Dove, boundThis è [[BoundThis]], args è [[BoundArguments]] seguito dagli argomenti passati dalla chiamata alla funzione.

+ +

Una funzione associata (bound function) può anche essere costruita usando l'operatore new: agendo in tal modo si comporta come se la funzione obiettivo fosse stata invece costruita. Il valore this fornito viene ignorato, mentre gli argomenti preposti sono forniti alla funzione emulata.

+ +

Esempi

+ +

Creare una funzione associata

+ +

L'uso più semplice di bind() è di creare una funzione che, indipendentemente da come viene chiamata, viene chiamata con un particolare valore. Un errore comune per i nuovi programmatori JavaScript consiste nell'estrarre un metodo da un oggetto, in seguito chiamare tale funzione e aspettarsi che utilizzi l'oggetto originale come tale (ad esempio, utilizzando tale metodo nel codice basato sul callback). Senza particolare cura, tuttavia, l'oggetto originale viene solitamente perso. La creazione di una funzione associata dalla funzione, utilizzando l'oggetto originale, risolve in modo chiaro questo problema:

+ +
this.x = 9;    // questo si riferisce all'oggetto "finestra" globale qui nel browser
+var module = {
+  x: 81,
+  getX: function() { return this.x; }
+};
+
+module.getX(); // 81
+
+var retrieveX = module.getX;
+retrieveX();
+// returns 9 - restituisce 9 - La funzione viene richiamata nell'ambito globale
+
+// Create a new function with 'this' bound to module
+// Crea una nuova funzione con 'this' associato al modulo
+// I nuovi programmatori potrebbero confondere il
+// global var x con la proprietà del modulo x var boundGetX = retrieveX.bind(module);
+boundGetX(); // 81
+
+ +

Funzioni parzialmente applicate

+ +

Il prossimo uso più semplice di bind() è quello di creare una funzione con argomenti iniziali pre-specificati. Questi argomenti (se presenti) seguono il valore fornito e vengono quindi inseriti all'inizio degli argomenti passati alla funzione di destinazione, seguiti dagli argomenti passati alla funzione associata, ogni volta che viene chiamata la funzione associata.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+// Crea una funzione con un argomento principale preimpostato
+var leadingThirtysevenList = list.bind(null, 37);
+
+var list2 = leadingThirtysevenList();
+// [37]
+
+var list3 = leadingThirtysevenList(1, 2, 3);
+// [37, 1, 2, 3]
+
+ +

Con setTimeout

+ +

Di default all'interno di {{domxref("window.setTimeout()")}}, la parola chiave this verrà impostata sull'oggetto {{ domxref("window") }} (or global). Quando si lavora con metodi di classe che richiedono questo this riferimento alle istanze di classe, è possibile associarlo esplicitamente alla funzione di callback, al fine di mantenere l'istanza.

+ +
function LateBloomer() {
+  this.petalCount = Math.floor(Math.random() * 12) + 1;
+}
+
+// Dichiarare apertura dopo un ritardo di 1 secondo
+LateBloomer.prototype.bloom = function() {
+  window.setTimeout(this.declare.bind(this), 1000);
+};
+
+LateBloomer.prototype.declare = function() {
+  console.log('Sono un bel fiore con ' +
+    this.petalCount + ' petali!');
+};
+
+var flower = new LateBloomer();
+flower.bloom();
+// dopo 1 secondo, attiva il metodo 'declare'
+ +

Funzioni associate utilizzate come costruttori

+ +
+

Warning: Questa sezione dimostra capacità JavaScript e documenta alcuni casi limite del metodo bind(). I metodi mostrati di seguito non sono il modo migliore di fare le cose e probabilmente non dovrebbero essere usati in nessun ambiente di produzione.

+
+ +

Le funzioni associate sono automaticamente utilizzabili con l'operatore {{jsxref("Operators/new", "new")}} per costruire nuove istanze create dalla funzione target. Quando una funzione associata viene utilizzata per costruire un valore, la condizione viene ignorata. Tuttavia, gli argomenti forniti sono ancora preposti alla chiamata del costruttore:

+ +
function Point(x, y) {
+  this.x = x;
+  this.y = y;
+}
+
+Point.prototype.toString = function() {
+  return this.x + ',' + this.y;
+};
+
+var p = new Point(1, 2);
+p.toString(); // '1,2'
+
+// non supportato nel polyfill di seguito,
+// funziona bene con il bind nativo:
+
+var YAxisPoint = Point.bind(null, 0/*x*/);
+
+
+var emptyObj = {};
+var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
+
+var axisPoint = new YAxisPoint(5);
+axisPoint.toString(); // '0,5'
+
+axisPoint instanceof Point; // true
+axisPoint instanceof YAxisPoint; // true
+new Point(17, 42) instanceof YAxisPoint; // true
+
+ +

Note that you need do nothing special to create a bound function for use with {{jsxref("Operators/new", "new")}}. The corollary is that you need do nothing special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using {{jsxref("Operators/new", "new")}}.

+ +
// Example can be run directly in your JavaScript console
+// ...continuing from above
+
+// Can still be called as a normal function
+// (although usually this is undesired)
+YAxisPoint(13);
+
+emptyObj.x + ',' + emptyObj.y;
+// >  '0,13'
+
+ +

If you wish to support the use of a bound function only using {{jsxref("Operators/new", "new")}}, or only by calling it, the target function must enforce that restriction.

+ +

Creating shortcuts

+ +

bind() is also helpful in cases where you want to create a shortcut to a function which requires a specific this value.

+ +

Take {{jsxref("Array.prototype.slice")}}, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

+ +
var slice = Array.prototype.slice;
+
+// ...
+
+slice.apply(arguments);
+
+ +

With bind(), this can be simplified. In the following piece of code, slice is a bound function to the {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the this value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional apply() calls can be eliminated:

+ +
// same as "slice" in the previous example
+var unboundSlice = Array.prototype.slice;
+var slice = Function.prototype.apply.bind(unboundSlice);
+
+// ...
+
+slice(arguments);
+
+ +

Polyfill

+ +

You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in implementations that do not natively support it.

+ +
if (!Function.prototype.bind) {
+  Function.prototype.bind = function(oThis) {
+    if (typeof this !== 'function') {
+      // closest thing possible to the ECMAScript 5
+      // internal IsCallable function
+      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
+    }
+
+    var aArgs   = Array.prototype.slice.call(arguments, 1),
+        fToBind = this,
+        fNOP    = function() {},
+        fBound  = function() {
+          return fToBind.apply(this instanceof fNOP
+                 ? this
+                 : oThis,
+                 aArgs.concat(Array.prototype.slice.call(arguments)));
+        };
+
+    if (this.prototype) {
+      // Function.prototype doesn't have a prototype property
+      fNOP.prototype = this.prototype;
+    }
+    fBound.prototype = new fNOP();
+
+    return fBound;
+  };
+}
+
+ +

Some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are:

+ + + +

If you choose to use this partial implementation, you must not rely on those cases where behavior deviates from ECMA-262, 5th edition! With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when bind() is widely implemented according to the specification.

+ +

Please check https://github.com/Raynos/function-bind for a more thorough solution!

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function.bind")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/call/index.html b/files/it/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..54acd401ca --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,175 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +
{{JSRef}}
+ +

Il metodo call() esegue una funzione con un dato valore this e argomenti passati singolarmente.

+ +
+

Note: Mentre la sintassi di questa funzione è quasi identica a quella di {{jsxref("Function.prototype.apply", "apply()")}}, la differenza fondamentale è che call() accetta una lista di argomenti mentre apply() accetta un singolo array di argomenti.

+
+ +
{{EmbedInteractiveExample("pages/js/function-call.html")}}
+ + + +

Sintassi

+ +
func.call([thisArg[, arg1, arg2, ...argN]])
+ +

Parametri

+ +
+
thisArg {{optional_inline}}
+
+

Il valore da usare come this quando si esegue func.

+ +
+

Attenzione: In certi casi, thisArg potrebbe non essere il valore reale visto dal metodo.

+ +

Se il metodo è una funzione in {{jsxref("Strict_mode", "non-strict mode", "", 1)}}, {{jsxref("Global_Objects/null", "null")}} e {{jsxref("Global_Objects/undefined", "undefined")}} sarà sostituito dall'oggetto globale e i valori di tipo primitiva verranno convertiti in oggetti.

+
+
+
arg1, arg2, ...argN {{optional_inline}}
+
Argomenti per la funzione.
+
+ +

Valore restituito

+ +

Il risultato dell'esecuzione della funzione con il this e gli argomenti specificati.

+ +

Descrizione

+ +

Il metodo call() consente a una funzione/metodo appartenente a un oggetto di essere essere assegnata e chiamata per un oggetto diverso..

+ +

call() fornisce un nuova valore di this alla funzione/metodo. Con call(), si può scrivere un metodo una volta ed ereditarlo in un altro oggetto senza dover riscrivere il metodo per il nuovo oggetto.

+ +

Esempi

+ +

Usare call per collegare costruttori per un oggetto

+ +

Si può usare call per collegare costruttori per un oggetto (simile a Java).

+ +

Nell'esempio seguente, il costruttore per l'oggetto Product è definito con 2 parametri: name e price.

+ +

Due altre funzioni, Food e Toy, invocano Product, passando this, name, e price. Product inizializza le proprietà name e price. Entrambe le funzioni specializzate definiscono la category.

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+
+const cheese = new Food('feta', 5);
+const fun = new Toy('robot', 40);
+
+ +

Usare call per invocare una funzione anonima

+ +

In questo esempio, viene create una funzione anonima e usato call per invocarla su ogni oggetto di un array.

+ +

Lo scopo principale della funzione anonima qui è di aggiungere una funzione print o ogni oggetto il quale è in grado di stampare il corretto indice dell'oggetto nell'array.

+ +
+

Passare l'oggetto come valore this non è strettamente necessario ma è fatto a scopo esplicativo.

+
+ +
const animals = [
+  { species: 'Lion', name: 'King' },
+  { species: 'Whale', name: 'Fail' }
+];
+
+for (let i = 0; i < animals.length; i++) {
+  (function(i) {
+    this.print = function() {
+      console.log('#' + i + ' ' + this.species
+                  + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

Usare call per invocare una funzione e specificare il contesto per  'this'

+ +

Nell'esempio sotto, quando viene eseguita greet, il valore di this verrà legato all'oggetto obj.

+ +
function greet() {
+  const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
+  console.log(reply);
+}
+
+const obj = {
+  animal: 'cats', sleepDuration: '12 and 16 hours'
+};
+
+greet.call(obj);  // cats typically sleep between 12 and 16 hours
+
+ +

Usare call per invocare una funzione senza specificare il primo parametro

+ +

Nell'esempio sotto, viene invocata la funzione display senza passare il primo parametro. Se il primo parametro non è passato il valore di this è legato all'oggetto globale.

+ +
var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call();  // sData value is Wisen
+ +
+

Attenzione: In strict mode il valore di this sarà undefined. Vedere sotto.

+
+ +
'use strict';
+
+var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call(); // Cannot read the property of 'sData' of undefined
+ +

Specifiche

+ + + + + + + + + + + + +
Specifiche
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Function.call")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/index.html b/files/it/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..4ef63fb80b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,237 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

+ +

gge

+ +

Syntax

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameters

+ +
+
arg1, arg2, ... argN
+
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Description

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +
+

Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Properties and Methods of Function

+ +

The global Function object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function prototype object

+ +

Properties

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

Methods

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function instances

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

A recursive shortcut to massively modify the DOM

+ +

Creating functions with the Function constructor is one of the ways to dynamically create an indeterminate number of new objects with some executable code into the global scope from a function. The following example (a recursive shortcut to massively modify the DOM) is impossible without the invocation of the Function constructor for each new query if you want to avoid closures.

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
+<script type="text/javascript">
+var domQuery = (function() {
+  var aDOMFunc = [
+    Element.prototype.removeAttribute,
+    Element.prototype.setAttribute,
+    CSSStyleDeclaration.prototype.removeProperty,
+    CSSStyleDeclaration.prototype.setProperty
+  ];
+
+  function setSomething(bStyle, sProp, sVal) {
+    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
+        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
+        aNodeList = bStyle ? this.cssNodes : this.nodes;
+
+    if (bSet && bStyle) { aArgs.push(''); }
+    for (
+      var nItem = 0, nLen = this.nodes.length;
+      nItem < nLen;
+      fAction.apply(aNodeList[nItem++], aArgs)
+    );
+    this.follow = setSomething.caller;
+    return this;
+  }
+
+  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
+  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
+  function getSelectors() { return this.selectors; };
+  function getNodes() { return this.nodes; };
+
+  return (function(sSelectors) {
+    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
+    oQuery.selectors = sSelectors;
+    oQuery.nodes = document.querySelectorAll(sSelectors);
+    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
+    oQuery.attributes = setAttribs;
+    oQuery.inlineStyle = setStyles;
+    oQuery.follow = getNodes;
+    oQuery.toString = getSelectors;
+    oQuery.valueOf = getNodes;
+    return oQuery;
+  });
+})();
+</script>
+</head>
+
+<body>
+
+<div class="testClass">Lorem ipsum</div>
+<p>Some text</p>
+<div class="testClass">dolor sit amet</div>
+
+<script type="text/javascript">
+domQuery('.testClass')
+  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
+  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
+</script>
+</body>
+
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

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

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/length/index.html b/files/it/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..6e305fb3ed --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,87 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +
{{JSRef}}
+ +

La proprietà length indica il numero di parametri che la funzione si aspetta di ricevere.

+ +

{{EmbedInteractiveExample("pages/js/function-length.html")}}

+ + + +
{{js_property_attributes(0,0,1)}}
+ +

Description

+ +

length è una proprietà di un oggetto {{jsxref("Function")}} che indica quanti argomenti la funzione si aspetta, cioè il numero di parametri formali. Questo numero esclude il {{jsxref("rest_parameters", "rest parameter", "", 1)}} e include solo i parametri prima del primo con un valore predefinito. Al contrario, {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} è locale a una funzione e fornisce il numero di argomenti effettivamente passati alla funzione.

+ +

Data property of the Function constructor

+ +

Il costruttore  {{jsxref("Function")}} è esso stesso un oggetto {{jsxref("Function")}}. La sua proprietà length ha valore 1. Gli attributi delle proprietà sono: Writable: false, Enumerable: false, Configurable: false.

+ +

Property of the Function prototype object

+ +

La proprietà length del prototype di un oggetto {{jsxref("Function")}} ha valore 0.

+ +

Examples

+ +
console.log(Function.length); /* 1 */
+
+console.log((function()        {}).length); /* 0 */
+console.log((function(a)       {}).length); /* 1 */
+console.log((function(a, b)    {}).length); /* 2 etc. */
+
+console.log((function(...args) {}).length);
+// 0, rest parameter is not counted
+
+console.log((function(a, b = 1, c) {}).length);
+// 1, only parameters before the first one with
+// a default value is counted
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}Gli attributi configurabili di queste proprietà diventano true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function.length")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/generator/index.html b/files/it/web/javascript/reference/global_objects/generator/index.html new file mode 100644 index 0000000000..b950dd8216 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/generator/index.html @@ -0,0 +1,187 @@ +--- +title: Generator +slug: Web/JavaScript/Reference/Global_Objects/Generator +tags: + - ECMAScript 2015 + - Generator + - JavaScript + - Legacy Generator + - Legacy Iterator + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Generator +--- +
{{JSRef}}
+ +

The Generator object is returned by a {{jsxref("Statements/function*", "generator function", "", 1)}} and it conforms to both the iterable protocol and the iterator protocol.

+ +

Syntax

+ +
function* gen() {
+  yield 1;
+  yield 2;
+  yield 3;
+}
+
+var g = gen(); // "Generator { }"
+ +

Methods

+ +
+
{{jsxref("Generator.prototype.next()")}}
+
Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression.
+
{{jsxref("Generator.prototype.return()")}}
+
Returns the given value and finishes the generator.
+
{{jsxref("Generator.prototype.throw()")}}
+
Throws an error to a generator.
+
+ +

Example

+ +

An infinite iterator

+ +
function* idMaker() {
+    var index = 0;
+    while(true)
+        yield index++;
+}
+
+var gen = idMaker(); // "Generator { }"
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+// ...
+ +

Legacy generator objects

+ +

Firefox (SpiderMonkey) also implements an earlier version of generators in JavaScript 1.7, where the star (*) in the function declaration was not necessary (you just use the yield keyword in the function body). However, legacy generators are deprecated. Do not use them; they are going to be removed ({{bug(1083482)}}).

+ +

Legacy generator methods

+ +
+
Generator.prototype.next() {{non-standard_inline}}
+
Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression. This corresponds to next() in the ES2015 generator object.
+
Generator.prototype.close() {{non-standard_inline}}
+
Closes the generator, so that when calling next() an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the return() method in the ES2015 generator object.
+
Generator.prototype.send() {{non-standard_inline}}
+
Used to send a value to a generator. The value is returned from the {{jsxref("Operators/yield", "yield")}} expression, and returns a value yielded by the next {{jsxref("Operators/yield", "yield")}} expression. send(x) corresponds to next(x) in the ES2015 generator object.
+
Generator.prototype.throw() {{non-standard_inline}}
+
Throws an error to a generator. This corresponds to the throw() method in the ES2015 generator object.
+
+ +

Legacy generator example

+ +
function* fibonacci() {
+  var a = yield 1;
+  yield a * 2;
+}
+
+var it = fibonacci();
+console.log(it);          // "Generator {  }"
+console.log(it.next());   // 1
+console.log(it.send(10)); // 20
+console.log(it.close());  // undefined
+console.log(it.next());   // throws StopIteration (as the generator is now closed)
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
+
+ +

See also

+ +

Legacy generators

+ + + +

ES2015 generators

+ + diff --git a/files/it/web/javascript/reference/global_objects/generator/next/index.html b/files/it/web/javascript/reference/global_objects/generator/next/index.html new file mode 100644 index 0000000000..03408534d5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/generator/next/index.html @@ -0,0 +1,157 @@ +--- +title: Generator.prototype.next() +slug: Web/JavaScript/Reference/Global_Objects/Generator/next +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/next +--- +
{{JSRef}}
+ +

Il metodo  next() ritorna un oggetto con due  proprietà  done and value. Puoi anche fornire un parametro al metodo next per trasmettere un valore al generatore.

+ +

Syntassi

+ +
gen.next(value)
+ +

Parametri

+ +
+
value
+
Il valore trasmesso al generatore
+
+ +

Return value

+ +

Un Oggetto con due proprietà:

+ + + +

Examples

+ +

Using next()

+ +

Il seguente esempio mostra semplice generatore e un oggetto che il metodo next ritorna:

+ +
function* gen() {
+  yield 1;
+  yield 2;
+  yield 3;
+}
+
+var g = gen(); // "Generator { }"
+g.next();      // "Object { value: 1, done: false }"
+g.next();      // "Object { value: 2, done: false }"
+g.next();      // "Object { value: 3, done: false }"
+g.next();      // "Object { value: undefined, done: true }"
+
+ +

Mandare valori al generatore

+ +

In questo esempio, next è stato chiamato con un valore. Nota che la prima chiamata non ha registrato nulla, perche il generatore non ha raccolto nulla inizialmente. 

+ +

 

+ +
function* gen() {
+  while(true) {
+    var value = yield null;
+    console.log(value);
+  }
+}
+
+var g = gen();
+g.next(1);
+// "{ value: null, done: false }"
+g.next(2);
+// "{ value: null, done: false }"
+// 2
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator.prototype.next', 'Generator.prototype.next')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator.prototype.next', 'Generator.prototype.next')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}13{{CompatGeckoDesktop(26)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatSafari(10)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support5.1{{CompatVersionUnknown}}{{CompatGeckoMobile(26)}}{{CompatUnknown}}{{CompatUnknown}}10
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/index.html b/files/it/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..3cddb3fc08 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/index.html @@ -0,0 +1,182 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - Refernce + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
{{jsSidebar("Objects")}}
+ +

Sommario

+ +

Questo capitolo documenta tutti gli oggetti standard predefiiti di JavaScript, con i loro metodi e le loro proprietà.

+ +

Il termine "oggetti globali" (o oggetti standard predefiniti) non va confuso con il termine oggetto globale. In questa documentazione, "oggetti globali" si riferisce agli oggetti nel contesto globale (ma solo se non viene utilizzata la modalità strict di ECMAScript5, altrimenti restituisce {{jsxref("Global_Objects/undefined", "undefined")}}). Si piuò accedere all'oggetto globale usando l'operatore {{jsxref("Operators/this", "this")}} nel contesto globale. Infatti il contesto globale consiste nell'insieme di tutte le properietà dell'oggetto globale.

+ +

Altri oggetti nel contesto globale possono essere creati dallo script o dall'applicazione utilizzata (ad esempio, un browser). Gli oggetti forniti dal browser sono documentati nella sezione API reference. Per altre informazioni riguardo la differenza tra il DOM e JavaScript base, vedi la panoramica sulle tecnologie JavaScript.

+ +
+

Oggetti standard (per categoria)

+ +

Valori

+ +

Varabili globali che rappresentano un valore semplice, non hanno altre proprietà o metodi.

+ + + +

Funzioni

+ +

Queste funzioni globali che vengono richiamate direttamente restituiscono direttamente il risultato al chiamante

+ + + +

Oggetti fondamentali

+ +

Oggetti generali di Javascrpt, sui quali sono basati tutti gli altri oggetti. Rappresentano oggetti, funzioni ed errori.

+ + + +

Numeri e date

+ +

Oggetti usati per rappresentare numeri, date e calcoli matematici.

+ + + +

Elaborazione del testo

+ +

Oggetti che rappresentano le stringe o il supporto per manipolarle.

+ + + +

Collezioni ordinate

+ +

Questi oggetti rappresentano delle collezioni di dati che sono ordinati secondo un indice. Includono array tipizzati ed costruttori simili ad array.

+ + + +

Collezioni chiave-valore

+ +

Oggetti che rappresentano collezzioni che usano delle chiavi per identificarne gli elementi; si può iterare attraverso gli elementi nell'ordine in cui sono stati inseriti.

+ + + +

Dati strutturati

+ +

Oggetti che rappresentano e interagiscono con buffer di dati e con dati codificati utilizzando JavaScript Object Notation (JSON).

+ + + +

Oggetti di controllo dell'astrazione

+ + + +

Reflection

+ + + +

Internazionalizzazione

+ +

Oggetti aggiunti a ECMAScript per le funzionalità che dipendono dalla lingua.

+ + + +

 

+ +

WebAssembly

+ + + +

 

+ +

Altro

+ + +
+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/infinity/index.html b/files/it/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..48b983e107 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,114 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La proprietà globale Infinity è un valore numerico che rappresenta l'infinito.

+ +

{{js_property_attributes(0,0,0)}}

+ +

Sintassi

+ +
Infinity 
+ +

Descrizione

+ +

Infinity è una proprietà dell'oggetto globale, ossia una variabile nell'ambito globale.

+ +

Il valore iniziale di Infinity è {{jsxref("Number.POSITIVE_INFINITY")}}. Il valore Infinity (infinito positivo) è maggiore di ogni altro numero. Matematicamente questo valore si comporta come l'infinito: per esempio, qualsiasi numero positivo moltipilicato per Infinity è uguale a Infinity, e qualsiasi numero diviso per Infinity è uguale a 0.

+ +

Secondo la specifica ECMAScript5, Infinity è accessibile in sola lettura (implementato in JavaScript 1.8.5 / Firefox 4).

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale. Implementato in JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.2', 'Infinity')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/isfinite/index.html b/files/it/web/javascript/reference/global_objects/isfinite/index.html new file mode 100644 index 0000000000..ee250b9410 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/isfinite/index.html @@ -0,0 +1,136 @@ +--- +title: isFinite() +slug: Web/JavaScript/Reference/Global_Objects/isFinite +translation_of: Web/JavaScript/Reference/Global_Objects/isFinite +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione globale isFinite() determina se il parametro passatole è un numero finito. Se necessario, il parametro viene prima convertito in un valore numerico.

+ +

Sintassi

+ +
isFinite(number)
+ +

Parametri

+ +
+
number
+
Il valore da controllare che sia finito.
+
+ +

Descrizione

+ +

isFinite è una funzione globale.

+ +

Puoi usare questa funzione per determinare se un numero è finito. La funzione isFinite restituisce false se il valore passatole è {{jsxref("NaN")}}, {{jsxref("Infinity")}} (infinito positivo) o -{{jsxref("Infinity")}} (infinito negativo); altrimenti restituisce true.

+ +

Esempi

+ +
isFinite(Infinity);  // false
+isFinite(NaN);       // false
+isFinite(-Infinity); // false
+
+isFinite(0);         // true
+isFinite(2e64);      // true
+
+
+isFinite("0");       // true, perché `"0"` viene convertito
+                     //       in un valore numerico, quindi
+                     //       in `0` e poi valutato.
+                     //       La funzione Number.isFinite("0"),
+                     //       più robusta, restituirebbe false.
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 2nd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/isnan/index.html b/files/it/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..db6ebc85d8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,176 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione isNaN() determina se un valore è {{jsxref("NaN")}} o no.

+ +
+

Nota: le conversioni di tipo nella funzione isNaN seguono delle regole {{jsxref("Global_Objects/isNaN", "particolari", "#Description", 1)}}: alternativamente per determinare se un valore non è un numero si può usare la funzione {{jsxref("Number.isNaN()")}}, definito in ECMAScript 6, o l'operatore {{jsxref("Operators/typeof", "typeof")}}.

+
+ +

Sintassi

+ +
isNaN(number)
+ +

Parametri

+ +
+
number
+
Il valore da controllare.
+
+ +

Descrizione

+ +

La necessità di una funzione isNaN()

+ +

A differenza di tutti gli altri valori in JavaScript, non è possibile usare gli operatori di uguaglianza (== e ===) per determinare se un valore è {{jsxref("NaN")}} oppure no, perché entrambe le uguaglianze NaN == NaN e NaN === NaN vengono considerate false. Ecco perché è necessaria una funzione isNaN().

+ +

L'origine del valore NaN

+ +

Il valore NaN è generato da un'operazione aritmetica il cui risultato è {{jsxref("undefined")}} o un valore non rappresentabile. Tali valori non rappresentano necessariamente un valore oltre i limiti. NaN può anche essere il risultato del trasformare valori non-numerici dai quali non è possibile ottenere un numero in numeri.

+ +

Per esempio, dividere zero per zero restituisce NaN, ma dividere un qualsiasi altro numero per zero no.

+ +

Comportamenti particolari

+ +

Già dalla prima versione della specifica della funzione isNaN, il suo comportamento con valori non-numerici può confondere. Quando il parametro della funzione isNaN non è di tipo {{jsxref("Number")}}, questo viene prima trasformato in un numero. Il test per determinare se il parametro è {{jsxref("NaN")}} viene effettuato sul valore convertito. Quindi per i valori non-numerici che possono essere trasformati in un numero diverso da NaN la funzione restituisce false. La stringa vuota, per esempio, suciramente non è un numero, ma la funzione restituisce false. La confusione nasce dal fatto che il termine "not a number" (rappresentato da NaN) ha un significato per i numeri rappresentati come valori a virgola mobile IEEE-754. La funzione dovrebbe quindi essere interpretata come "È questo valore, quando convertito in un numero, un valore "Not a Number" secondo lo standard IEEE-754?"

+ +

La prossima versione di ECMAScript (ES6) definiesce la funzione {{jsxref("Number.isNaN()")}}. Number.isNaN(), che ritorna false per tutti i valori non-numerici, sarà un metodo affidabile per sapere se un numero è NaN o no. In assenza di Number.isNaN, l'espressione (x !== x) è il metodo più affidabile per determinare se un numero è NaN oppure no, perché evita i falsi positivi generati dalla funzione isNaN().

+ +

Esempi

+ +
var x = NaN;
+isNaN(x);        // true
+Number.isNaN(x); // true
+x !== x;         // true
+
+var x = undefined;
+isNaN(x);        // true, perché undefined viene convertito in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+
+var x = {};
+isNaN(x);        // true, perché {} viene convertito in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+
+isNaN(true);     // false, perché true viene convertito in 1
+isNaN(null);     // false, perché null viene convertito in 0
+isNaN(37);       // false
+
+// Stringhe
+isNaN("37");     // false, perché "37" viene convertito in 37
+isNaN("37.37");  // false, perché "37.37" viene convertito in 37.37
+isNaN("");       // false, perché una stringa vuota viene convertita in 0
+isNaN(" ");      // false, perché una stringa con soli spazi viene convertita in 0
+
+// !!! Ecco un esempio di falso positivo
+var x = "37ab";
+isNaN(x);        // true, perché "37ab" viene convertito in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+
+// Date
+isNaN(new Date()); // false, perché una data che viene convertita in un
+                   //        numero ritorna un valore intero
+
+var x = new Date().toString();
+isNaN(x);        // true, perché il metodo new Date().toString() restituisce una
+                 //       stringa alfanumerica, che viene convertita in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/json/index.html b/files/it/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..caa08b766f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,244 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - NeedsTranslation + - Object + - Reference + - TopicStub + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef}}
+ +

The JSON object contains methods for parsing JavaScript Object Notation ({{glossary("JSON")}}) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

+ +

Description

+ +

JavaScript Object Notation

+ +

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and {{jsxref("null")}}. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON, and some JSON is not JavaScript. See also JSON: The JavaScript subset that isn't.

+ + + + + + + + + + + + + + + + + + + + + + + +
JavaScript and JSON differences
JavaScript typeJSON differences
Objects and ArraysProperty names must be double-quoted strings; trailing commas are forbidden.
NumbersLeading zeros are prohibited; a decimal point must be followed by at least one digit.
Strings +

Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:

+ +
+var code = '"\u2028\u2029"';
+JSON.parse(code); // works fine
+eval(code); // fails
+
+
+ +

The full JSON syntax is as follows:

+ +
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+ +

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

+ +

Methods

+ +
+
{{jsxref("JSON.parse()")}}
+
Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
+
{{jsxref("JSON.stringify()")}}
+
Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
+
+ +

Polyfill

+ +

The JSON object is not supported in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of JSON object in implementations which do not natively support it (like Internet Explorer 6).

+ +

The following algorithm is an imitation of the native JSON object:

+ +
if (!window.JSON) {
+  window.JSON = {
+    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
+    stringify: (function () {
+      var toString = Object.prototype.toString;
+      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
+      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
+      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
+      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
+      return function stringify(value) {
+        if (value == null) {
+          return 'null';
+        } else if (typeof value === 'number') {
+          return isFinite(value) ? value.toString() : 'null';
+        } else if (typeof value === 'boolean') {
+          return value.toString();
+        } else if (typeof value === 'object') {
+          if (typeof value.toJSON === 'function') {
+            return stringify(value.toJSON());
+          } else if (isArray(value)) {
+            var res = '[';
+            for (var i = 0; i < value.length; i++)
+              res += (i ? ', ' : '') + stringify(value[i]);
+            return res + ']';
+          } else if (toString.call(value) === '[object Object]') {
+            var tmp = [];
+            for (var k in value) {
+              if (value.hasOwnProperty(k))
+                tmp.push(stringify(k) + ': ' + stringify(value[k]));
+            }
+            return '{' + tmp.join(', ') + '}';
+          }
+        }
+        return '"' + value.toString().replace(escRE, escFunc) + '"';
+      };
+    })()
+  };
+}
+
+ +

More complex well-known polyfills for the JSON object are JSON2 and JSON3.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/json/parse/index.html b/files/it/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..f5c823ddf1 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,126 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +tags: + - ECMAScript5 + - JSON + - JavaScript + - Riferimento + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +
{{JSRef}}
+ +

Il metodo JSON.parse() analizza una stringa JSON, costruendo il valore JavaScript o l'oggetto descritto dalla stringa. È possibile fornire una funzione reviver opzionale per eseguire una trasformazione sull'oggetto risultante prima che venga restituito.

+ +
{{EmbedInteractiveExample("pages/js/json-parse.html")}}
+ + + +

Sintassi

+ +
JSON.parse(text[, reviver])
+ +

Parametri

+ +
+
text
+
La stringa da analizzare come JSON. Vedi l'oggetto {{jsxref("JSON")}} per una descrizione della sintassi JSON.
+
reviver {{optional_inline}}
+
Se una funzione, questo prescrive come viene trasformato il valore originariamente prodotto dall'analisi, prima di essere restituito.
+
+ +

Valore di ritorno

+ +

{{jsxref("Object")}} corrispondente al parametro JSON text dato.

+ +

Eccezione

+ +

Genera un errore {{jsxref("SyntaxError")}} se la stringa da analizzare non è JSON valida.

+ +

Esempi

+ +

Utilizzare JSON.parse()

+ +
JSON.parse('{}');              // {}
+JSON.parse('true');            // true
+JSON.parse('"foo"');           // "foo"
+JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
+JSON.parse('null');            // null
+
+ +

Usare il parametro reviver

+ +

Se viene specificato un reviver, il valore calcolato dall'analisi viene trasformato prima di essere restituito. In particolare, il valore calcolato e tutte le sue proprietà (che iniziano con le proprietà più nidificate e procedono al valore originale stesso) vengono eseguite individualmente attraverso il reviver. Quindi viene chiamato, con l'oggetto contenente la proprietà da elaborare come this, e con il nome della proprietà come stringa e il valore della proprietà come argomenti. Se la funzione  reviver restituisce {{jsxref("undefined")}} (o non restituisce alcun valore, ad esempio, se l'esecuzione cade al termine della funzione), la proprietà viene cancellata dall'oggetto. In caso contrario, la proprietà viene ridefinita come il valore restituito.

+ +

Se reviver trasforma solo alcuni valori e non altri, sii certo di restituire tutti i valori non trasformati così come sono, altrimenti verranno eliminati dall'oggetto risultante.

+ +
JSON.parse('{"p": 5}', (key, value) =>
+  typeof value === 'number'
+    ? value * 2 // ritorna: value * 2 per i numeri
+    : value     // restituisce tutto il resto invariato
+);
+
+// { p: 10 }
+
+JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
+  console.log(key); // registra il nome della proprietà corrente, l'ultimo è "".
+  return value;     // restituisce il valore della proprietà invariato.
+});
+
+// 1
+// 2
+// 4
+// 6
+// 5
+// 3
+// ""
+
+ +

JSON.parse() non consente virgole finali

+ +
// both will throw a SyntaxError
+JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
+ +

Compatiblità con i browser

+ +
+ + +

{{Compat("javascript.builtins.JSON.parse")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/json/stringify/index.html b/files/it/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..9a0bf5f812 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,325 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +
{{JSRef}}
+ +
 
+ +

Il metodo JSON.stringify() converte un oggetto o un valore JavaScript in una stringa JSON, sostituendo facoltativamente i valori se viene specificata una funzione sostitutiva o facoltativamente includendo solo le proprietà specificate se viene specificato un array replacer.

+ +
{{EmbedInteractiveExample("pages/js/json-stringify.html")}}
+ + + +

Sintassi

+ +
JSON.stringify(value[, replacer[, space]])
+ +

Parametri

+ +
+
value
+
Il valore da convertire in stringa JSON.
+
replacer{{optional_inline}}
+
Una funzione che altera il processo di conversione, o un array di {{jsxref("String")}} e {{jsxref("Number")}} che contiene le proprietà dell'oggetto che devono essere incluse nella stringa JSON. Se il valore è null o non è specificato, tutte le proprietà dell'oggetto sono incluse nel risultato.
+
space{{optional_inline}}
+
Un oggetto {{jsxref("String")}} o {{jsxref("Number")}} che viene utilizzato per inserire uno spazio bianco nella stringa JSON di output a fini di leggibilità.Se questo è un Number, indica il numero di caratteri dello spazio da usare come spazio bianco; questo numero è limitato a 10 (se è maggiore, il valore è solo 10).Valori inferiori a 1 indicano che non deve essere usato alcuno spazio.
+
+

Se si tratta di una  String, la stringa (i primi 10 caratteri della stringa, se è più lunga di quella) viene utilizzata come spazio bianco. Se questo parametro non viene fornito (o è {{JSxRef("null")}}), non viene utilizzato alcuno spazio bianco.

+ +

Valore di ritorno

+ +

Una stringa JSON che rappresenta il valore dato.

+ +

Eccezioni

+ +

Genera un'eccezione {{JSxRef("TypeError")}} ("valore dell'oggetto ciclico") quando viene trovato un riferimento circolare.

+
+
+ +

Descrizione

+ +

JSON.stringify() converte un valore in notazione JSON che lo rappresenta:

+ + + +
JSON.stringify({});                  // '{}'
+JSON.stringify(true);                // 'true'
+JSON.stringify('foo');               // '"foo"'
+JSON.stringify([1, 'false', false]); // '[1,"false",false]'
+JSON.stringify({ x: 5 });            // '{"x":5}'
+
+JSON.stringify({ x: 5, y: 6 });
+// '{"x":5,"y":6}' or '{"y":6,"x":5}'
+JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
+// '[1,"false",false]'
+
+// Simboli:
+JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
+// '{}'
+JSON.stringify({ [Symbol('foo')]: 'foo' });
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
+  if (typeof k === 'symbol') {
+    return 'a symbol';
+  }
+});
+// '{}'
+
+// Proprietà non enumerabili:
+JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
+// '{"y":"y"}'
+
+
+ +

Il parametro replacer

+ +

Il parametro replacer può essere una funzione o un array.

+ +

Come una funzione, prende due parametri: la chiave e il valore che si sta stringendo. L'oggetto in cui è stata trovata la chiave viene fornito come il parametro this del replacer.

+ +

Inizialmente, la funzione replacer viene chiamata con una stringa vuota come chiave che rappresenta l'oggetto da stringificare. Viene quindi chiamato per ogni proprietà sull'oggetto o sull'array da stringificare.

+ + + +
Nota: Non è possibile utilizzare la replacerfunzione per rimuovere i valori da una matrice. Se si restituisce undefinedo una funzione, nullviene invece utilizzata.
+ +
Se desideri che il replacer distingua un oggetto iniziale da una chiave con una proprietà stringa vuota (poiché entrambi fornirebbero la stringa vuota come chiave e potenzialmente un oggetto come valore), sarà necessario tenere traccia del conteggio dell'iterazione (se è al di là della prima iterazione, è una vera e propria chiave di stringa vuota).
+ +

Esempio di replacer, come funzione

+ +
function replacer(key, value) {
+  // Filtraggio delle proprietà
+  if (typeof value === 'string') {
+    return undefined;
+  }
+  return value;
+}
+
+var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
+JSON.stringify(foo, replacer);
+// Risultato: '{"week":45,"month":7}'
+
+ +

Esempio di replacer, come array

+ +

Se replacer è un array, i valori dell'array indicano i nomi delle proprietà nell'oggetto che dovrebbero essere incluse nella stringa JSON risultante.

+ +
JSON.stringify(foo, ['week', 'month']);
+// '{"week":45,"month":7}', mantiene solo le proprietà "week" e "month"
+
+ +

Il parametro space

+ +

L'argomento space può essere usato per controllare la spaziatura nella stringa finale.

+ + + +
JSON.stringify({ a: 2 }, null, ' ');
+// '{
+//  "a": 2
+// }'
+ +

L'utilizzo di un carattere di tabulazione simula l'aspetto standard di tipo "pretty-print":

+ +
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
+// restituisce la stringa:
+// '{
+//     "uno": 1,
+//     "dos": 2
+// }'
+
+ +

Comportamento di toJSON()

+ +

Se un oggetto da stringificare ha una proprietà denominata il toJSON cui valore è una funzione, il metodo toJSON() personalizza il comportamento di stringificazione JSON: invece dell'oggetto serializzato, il valore restituito dal metodo toJSON() quando chiamato verrà serializzato. JSON.stringify() chiama toJSON con un parametro:

+ + + +

Per esempio:

+ +
var obj = {
+    data: 'data',
+
+    toJSON(key){
+        if(key)
+            return `Ora sono un oggetto nidificato sotto chiave '${key}'`;
+
+        else
+            return this;
+    }
+};
+
+JSON.stringify(obj);
+// '{"data":"data"}'
+
+JSON.stringify({ obj })
+// '{"obj":"Ora sono un oggetto nidificato sotto chiave 'obj'"}'
+
+JSON.stringify([ obj ])
+// '["Ora sono un oggetto nidificato sotto chiave '0'"]'
+
+ +

Problema con JSON.stringify() durante la serializzazione di riferimenti circolari

+ +

Nota che poiché il Formato JSON non supporta i riferimenti agli oggetti (sebbene esista una bozza IETF), {{JSxRef("TypeError")}} verrà generato un se si tenta di codificare un oggetto con riferimenti circolari.

+ +
const circularReference = {};
+circularReference.myself = circularReference;
+
+// La serializzazione dei riferimenti circolari genera "TypeError: valore dell'oggetto ciclico"
+JSON.stringify(circularReference);
+
+ +

Per serializzare i riferimenti circolari è possibile utilizzare una libreria che li supporta (ad es. cycle.js di Douglas Crockford) o implementare una soluzione autonomamente, che richiederà la ricerca e la sostituzione (o la rimozione) dei riferimenti ciclici mediante valori serializzabili.

+ +

Problema con plain  JSON.stringify per l'uso come JavaScript

+ +

Storicamente, JSON non era un sottoinsieme completamente rigido di JavaScript. I punti del codice letterale U + 2028 LINE SEPARATOR e U + 2029 PARAGRAPH SEPARATOR potrebbero apparire letteralmente in stringhe letterali e nomi di proprietà nel testo JSON. Ma non potevano apparire letteralmente in un contesto simile nel testo JavaScript - solo usando escape Unicode come \u2028\u2029.  Questo è cambiato di recente: ora entrambi i punti di codice possono apparire letteralmente nelle stringhe in JSON e JavaScript entrambi.

+ +

Pertanto, se è richiesta la compatibilità con i motori JavaScript precedenti, è pericoloso sostituire direttamente la stringa restituita da JSON.stringify una stringa JavaScript da passare a eval new Function o come parte di un URL JSONP e può essere utilizzata la seguente utility:

+ +
function jsFriendlyJSONStringify (s) {
+    return JSON.stringify(s).
+        replace(/\u2028/g, '\\u2028').
+        replace(/\u2029/g, '\\u2029');
+}
+
+var s = {
+    a: String.fromCharCode(0x2028),
+    b: String.fromCharCode(0x2029)
+};
+try {
+    eval('(' + JSON.stringify(s) + ')');
+} catch (e) {
+    console.log(e); // "SyntaxError: unterminated string literal"
+}
+
+// No need for a catch
+eval('(' + jsFriendlyJSONStringify(s) + ')');
+
+// console.log in Firefox scolla l'Unicode se
+//   connesso alla console, quindi usiamo alert
+alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}
+
+ +
+

Note: Non è garantito che le proprietà degli oggetti non array vengano sottoposte a stringa in qualsiasi ordine particolare. Non fare affidamento sull'ordinamento di proprietà all'interno dello stesso oggetto all'interno della stringa.

+
+ +
var a = JSON.stringify({ foo: "bar", baz: "quux" })
+//'{"foo":"bar","baz":"quux"}'
+var b = JSON.stringify({ baz: "quux", foo: "bar" })
+//'{"baz":"quux","foo":"bar"}'
+console.log(a !== b) // true
+
+// alcune funzioni di memoizzazione usano JSON.stringify per serializzare gli argomenti,
+// mancando la cache quando si incontra lo stesso oggetto come sopra
+
+ +

Esempio di utilizzo JSON.stringify() con localStorage

+ +

Nel caso in cui desideri archiviare un oggetto creato dall'utente e consentirne il ripristino anche dopo la chiusura del browser, nell'esempio seguente è disponibile un modello per l'applicabilità di JSON.stringify():

+ +
// Creare un esempio di JSON
+var session = {
+  'screens': [],
+  'state': true
+};
+session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
+session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
+session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
+session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
+session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
+session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });
+
+// Conversione della stringa JSON con JSON.stringify()
+// quindi salva con localStorage nel nome della sessione
+localStorage.setItem('session', JSON.stringify(session));
+
+// Esempio di come trasformare la stringa generata tramite
+// JSON.stringify() e salvare nuovamente in localStorage nell'oggetto JSON
+var restoredSession = JSON.parse(localStorage.getItem('session'));
+
+// Ora la variabile restoreSession contiene l'oggetto che è stato salvato
+// in localStorage
+console.log(restoredSession);
+
+ +

Well-formed JSON.stringify()

+ +

Engines implementing the well-formed JSON.stringify specification will stringify lone surrogates -- any code point from U+D800 to U+DFFF -- using Unicode escape sequences rather than literally.  Before this change JSON.stringify would output lone surrogates if the input contained any lone surrogates; such strings could not be encoded in valid UTF-8 or UTF-16:

+ +
JSON.stringify("\uD800"); // '"�"'
+ +

Ma con questo cambiamento JSON.stringify rappresentano surrogati solitari usando sequenze di escape JSON che possono essere codificate in UTF-8 o UTF-16 validi:

+ +
JSON.stringify("\uD800"); // '"\\ud800"'
+ +

Questo cambiamento dovrebbe essere retrocompatibile fin tanto che si passa il risultato di JSON.stringify API come JSON.parse quella che accetterà qualsiasi testo JSON valido, in quanto tratterà le escape Unicode dei surrogati soli come identici ai surrogati solitari stessi.  Solo se stai interpretando direttamente il risultato di JSON.stringify hai bisogno di gestire attentamente JSON.stringify le due possibili codifiche di questi punti di codice.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}{{Spec2('ES5.1')}}Definzione iniziale. Implementato su JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ESDraft')}} 
+ +

Compatiblità con i browser

+ +
+ + +

{{Compat("javascript.builtins.JSON.stringify")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/clear/index.html b/files/it/web/javascript/reference/global_objects/map/clear/index.html new file mode 100644 index 0000000000..85918279ad --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/clear/index.html @@ -0,0 +1,76 @@ +--- +title: Map.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Map/clear +tags: + - ECMAScript 2015 + - JavaScript + - Map + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear +--- +
{{JSRef}}
+ +

Il metodo clear() rimuove tutti gli elementi di un oggetto Map.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-clear.html")}}
+ + + +

Sintassi

+ +
myMap.clear();
+ +

Valore di ritorno

+ +

{{jsxref("undefined")}}.

+ +

Esempi

+ +

Utilizzare il metodo clear

+ +
var myMap = new Map();
+myMap.set('bar', 'baz');
+myMap.set(1, 'foo');
+
+myMap.size;       // 2
+myMap.has('bar'); // true
+
+myMap.clear();
+
+myMap.size;       // 0
+myMap.has('bar')  // false
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Map.clear")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/delete/index.html b/files/it/web/javascript/reference/global_objects/map/delete/index.html new file mode 100644 index 0000000000..18c511b3eb --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/delete/index.html @@ -0,0 +1,74 @@ +--- +title: Map.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Map/delete +translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete +--- +
{{JSRef}}
+ +

Il metododelete() rimuove l'elemento specificato da un oggetto Map selezionandolo in base alla chiave.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-delete.html")}}
+ + + +

Sintassi

+ +
myMap.delete(key);
+ +

Parametri

+ +
+
key
+
La chiave dell'elemento da rimuovere dall'oggetto Map.
+
+ +

Valore ritornato

+ +

true se un elemento con la chiave specificata esisteva nell'oggetto Map ed è stato ora rimosso, o false se non esisteva alcun elemento con la chiave specificata.

+ +

Esempi

+ +

Usare delete()

+ +
var myMap = new Map();
+myMap.set('bar', 'foo');
+
+myMap.delete('bar'); // Ritorna true. Rimosso con successo.
+myMap.has('bar');    // Ritorna false. L'elemento "bar" non è più presente.
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ES2015')}}Initial definition.
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.Map.delete")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/foreach/index.html b/files/it/web/javascript/reference/global_objects/map/foreach/index.html new file mode 100644 index 0000000000..ab1c69a310 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/foreach/index.html @@ -0,0 +1,88 @@ +--- +title: Map.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Map/forEach +tags: + - ECMAScript 2015 + - JavaScript + - Map + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Map/forEach +--- +
{{JSRef}}
+ +

Il metodo forEach() esegue una funzione fornita come argomento una volta per ogni coppia key/value nell'oggetto Map, secondo l'ordine dell'inseriemento dei valori.

+ +

Sintassi

+ +
myMap.forEach(callback[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione da eseguire per ogni elemento.
+
thisArg
+
Valore da usare come this quando si esegue callback.
+
+ +

Descrizione

+ +

Il metodo forEach esegue il callback passato come parametro una volta per ogni key della map esistente. Non è invocato per key che sono state cancellate. Comunque, è invocato per valori che sono presenti ma hanno valore undefined.

+ +

callback è invocato con tre argomenti:

+ + + +

Se il parametro thisArg è fornito al forEach, sarà passato al callback quando viene invocato, per essere usato come suo valore this.  In caso contrario, sarà passato il valore undefined per essere usato come valore this. Il valore this visibile definitivamente dal callbackè determinato secondo le normali regole per determinare il this visibile da una funzione.

+ +

Il range di elementi processati da forEach è determinato anteriormente alla prima invocazione del callback. Gli elementi che sono aggiunti all'oggetto Map dopo che la chiamata a forEach inizi non saranno visitati dal callback. Se eleemnti esistenti dell'oggetto Map vengono cambiati, o cancellati, il loro valore passato al callback sarà il valore nel momento in cui il forEach li visita; elementi che vengono cancellati non sono visitati.

+ +

forEach esegue la funzione callback una volta per ogni elemento nell'oggetto Map; non restituisce alcun valore.

+ +

Esempi

+ +

Stampare il contenuto di un oggetto Map

+ +

Il seguente codice stampa nella console una riga per ogni elemento in un oggetto Map:

+ +
function logMapElements(value, key, map) {
+    console.log("m[" + key + "] = " + value);
+}
+Map([["foo", 3], ["bar", {}], ["baz", undefined]]).forEach(logMapElements);
+// logs:
+// "m[foo] = 3"
+// "m[bar] = [object Object]"
+// "m[baz] = undefined"
+
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificationStatoCommento
{{SpecName('ES6', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}{{Spec2('ES6')}}Definizione iniziale.
+ +

Compatibilità dei browser

+ +

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

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/index.html b/files/it/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..58ee676d23 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,439 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript6 + - Experimental + - JavaScript + - Map + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

The Map object is a simple key/value map. Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

+ +

Syntax

+ +
new Map([iterable])
+
+ +

Parameters

+ +
+
iterable
+
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair is added to the new Map. null is treated as undefined.
+
+ +

Description

+ +

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.

+ +

Key equality

+ +

Key equality is based on the "same-value" algorithm: NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. In earlier versions of the ECMAScript 6 draft -0 and +0 were considered distinct (even though -0 === +0), this has been changed in later versions and has been adapted in Gecko 29 {{geckoRelease("29")}} ({{bug("952870")}}) and a recent nightly Chrome.

+ +

Objects and maps compared

+ +

{{jsxref("Object", "Objects")}} are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better:

+ + + +

This does not mean you should use Maps everywhere, objects still are used in most cases. Map instances are only useful for collections, and you should consider adapting your code where you have previously used objects for such. Objects shall be used as records, with fields and methods.
+ If you're still not sure which one to use, ask yourself the following questions:

+ + + +

Those all are signs that you want a Map for a collection. If in contrast you have a fixed amount of keys, operate on them individually, and distinguish between their usage, then you want an object.

+ +

Properties

+ +
+
Map.length
+
The value of the length property is 0.
+
{{jsxref("Map.@@species", "get Map[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Map.prototype")}}
+
Represents the prototype for the Map constructor. Allows the addition of properties to all Map objects.
+
+ +

Map instances

+ +

All Map instances inherit from {{jsxref("Map.prototype")}}.

+ +

Properties

+ +

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

+ +

Methods

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

+ +

Examples

+ +

Using the Map object

+ +
var myMap = new Map();
+
+var keyString = "a string",
+    keyObj = {},
+    keyFunc = function () {};
+
+// setting the values
+myMap.set(keyString, "value associated with 'a string'");
+myMap.set(keyObj, "value associated with keyObj");
+myMap.set(keyFunc, "value associated with keyFunc");
+
+myMap.size; // 3
+
+// getting the values
+myMap.get(keyString);    // "value associated with 'a string'"
+myMap.get(keyObj);       // "value associated with keyObj"
+myMap.get(keyFunc);      // "value associated with keyFunc"
+
+myMap.get("a string");   // "value associated with 'a string'"
+                         // because keyString === 'a string'
+myMap.get({});           // undefined, because keyObj !== {}
+myMap.get(function() {}) // undefined, because keyFunc !== function () {}
+
+ +

Using NaN as Map keys

+ +

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works, because NaNs are indistinguishable from each other:

+ +
var myMap = new Map();
+myMap.set(NaN, "not a number");
+
+myMap.get(NaN); // "not a number"
+
+var otherNaN = Number("foo");
+myMap.get(otherNaN); // "not a number"
+
+ +

Iterating Maps with for..of

+ +

Maps can be iterated using a for..of loop:

+ +
var myMap = new Map();
+myMap.set(0, "zero");
+myMap.set(1, "one");
+for (var [key, value] of myMap) {
+  console.log(key + " = " + value);
+}
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+for (var key of myMap.keys()) {
+  console.log(key);
+}
+// Will show 2 logs; first with "0" and second with "1"
+
+for (var value of myMap.values()) {
+  console.log(value);
+}
+// Will show 2 logs; first with "zero" and second with "one"
+
+for (var [key, value] of myMap.entries()) {
+  console.log(key + " = " + value);
+}
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

Iterating Maps with forEach()

+ +

Maps can be iterated using the forEach() method:

+ +
myMap.forEach(function(value, key) {
+  console.log(key + " = " + value);
+}, myMap)
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

Relation with Array objects

+ +
var kvArray = [["key1", "value1"], ["key2", "value2"]];
+
+// Use the regular Map constructor to transform a 2D key-value Array into a map
+var myMap = new Map(kvArray);
+
+myMap.get("key1"); // returns "value1"
+
+// Use the spread operator to transform a map into a 2D key-value Array.
+console.log(uneval([...myMap])); // Will show you exactly the same Array as kvArray
+
+// Or use the spread operator on the keys or values iterator to get
+// an array of only the keys or values
+console.log(uneval([...myMap.keys()])); // Will show ["key1", "key2"]
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-map-objects', 'Map')}}{{Spec2('ES6')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{ CompatChrome(38) }} [1]

+
{{ CompatGeckoDesktop("13") }}11257.1
Constructor argument: new Map(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Map.clear(){{ CompatChrome(31) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("19")}}11257.1
Map.keys(), Map.values(), Map.entries(){{ CompatChrome(37) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("20")}}{{CompatNo}}257.1
Map.forEach(){{ CompatChrome(36) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("25")}}11257.1
Key equality for -0 and 0{{ CompatChrome(34) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Map(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{ CompatGeckoDesktop("42") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatChrome(38) }} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Map(iterable){{CompatNo}}{{ CompatChrome(38) }}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Map.clear(){{CompatNo}}{{ CompatChrome(31) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Map.keys(), Map.values(), Map.entries(){{CompatNo}}{{ CompatChrome(37) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("20")}}{{CompatNo}}{{CompatNo}}8
Map.forEach(){{CompatNo}}{{ CompatChrome(36) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Key equality for -0 and 0{{CompatNo}}{{ CompatChrome(34) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Map(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Starting with Chrome 31, the feature was available behind a preference. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/abs/index.html b/files/it/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..6dcf7a7dd6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,95 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +
{{JSRef}}
+ +

La funzione Math.abs() ritorna il valore assoluto di un numero, ovvero

+ +

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

+ +

Sintassi

+ +
Math.abs(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

Il valore assoluto del numero passato come parametro.

+ +

Descrizione

+ +

Siccome abs() è un metodo statico di Math, viene sempre utilizzato come Math.abs() piuttosto che come metodo di un oggetto Math creato in precedenza (Math non è un costruttore).

+ +

Esempi

+ +

Comportamento di Math.abs()

+ +

Passando un oggetto vuoto, un array con più di un elemento, una stringa non numerica o una variabile {{jsxref("undefined")}}/empty il valore di ritorno sarà {{jsxref("NaN")}}. Passando {{jsxref("null")}}, una stringa vuota o un array vuoto, il valore di ritorno sarà 0.

+ +
Math.abs('-1');     // 1
+Math.abs(-2);       // 2
+Math.abs(null);     // 0
+Math.abs('');       // 0
+Math.abs([]);       // 0
+Math.abs([2]);      // 2
+Math.abs([1,2]);    // NaN
+Math.abs({});       // NaN
+Math.abs('string'); // NaN
+Math.abs();         // NaN
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i Browser

+ + + +

{{Compat("javascript.builtins.Math.abs")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/acos/index.html b/files/it/web/javascript/reference/global_objects/math/acos/index.html new file mode 100644 index 0000000000..b872e04ab2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/acos/index.html @@ -0,0 +1,94 @@ +--- +title: Math.acos() +slug: Web/JavaScript/Reference/Global_Objects/Math/acos +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acos +--- +
{{JSRef}}
+ +

La funzione Math.acos() ritorna l'arcocoseno (in radianti) di un numero, ovvero

+ +

x[-1;1],Math.acos(x)=arccos(x)= the unique y[0;π]such thatcos(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x

+ +

Sintassi

+ +
Math.acos(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

L'arcocoseno (in radianti) del numero passato come parametro se quest'ultimo si trova tra i valori -1 e 1; altrimenti ritorna {{jsxref("NaN")}}.

+ +

Descrizione

+ +

Il metodo Math.acos() ritorna un valore numerico compreso tra 0 and π radianti per x compreso tra -1 e 1. Se il valore di x si trova al di fuori di questo range il metodo ritorna {{jsxref("NaN")}}.

+ +

Siccome acos() è un metodo statico di Math, viene sempre usato come Math.acos() piuttosto che come metodo di un oggetto Math creato in precedenza (Math non è un costruttore).

+ +

Esempi

+ +

Math.acos()

+ +
Math.acos(-2);  // NaN
+Math.acos(-1);  // 3.141592653589793
+Math.acos(0);   // 1.5707963267948966
+Math.acos(0.5); // 1.0471975511965979
+Math.acos(1);   // 0
+Math.acos(2);   // NaN
+
+ +

Per valori inferiori a -1 o maggiori di 1, Math.acos() ritorna {{jsxref("NaN")}}.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.2', 'Math.acos')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.acos', 'Math.acos')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.acos', 'Math.acos')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei Browser

+ + + +

{{Compat("javascript.builtins.Math.acos")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/atan/index.html b/files/it/web/javascript/reference/global_objects/math/atan/index.html new file mode 100644 index 0000000000..9be8920214 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/atan/index.html @@ -0,0 +1,100 @@ +--- +title: Math.atan() +slug: Web/JavaScript/Reference/Global_Objects/Math/atan +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan +--- +
{{JSRef}}
+ +

La funzione Math.atan() restituisce l'arcotangente (in radianti) di un numero, definita come

+ +

Math.atan(x)=arctan(x)= l'unica y[-π2;π2]tale chetan(y)=x\mathtt{\operatorname{Math.atan}(x)} = \arctan(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \tan(y) = x

+ +

Sintassi

+ +
Math.atan(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

L'arcotangente (in radianti) del numero dato x.

+ +

Descrizione

+ +

Il metodo Math.atan() ritorna un valore numerico compreso tra -π2-\frac{\pi}{2} e π2\frac{\pi}{2} radianti.

+ +

Poiché atan() è un membro statico di Math, è da usarsi sempre nella forma Math.atan(), piuttosto che come un metodo di un oggetto Math creato (Math non è il costruttore di una classe).

+ +

Esempî

+ +

Using Math.atan()

+ +
Math.atan(1);   // 0.7853981633974483
+Math.atan(0);   // 0
+Math.atan(-0);  // -0
+
+Math.atan(Infinity);   //  1.5707963267948966
+Math.atan(-Infinity);  // -1.5707963267948966
+
+/*
+L'angolo che la retta su cui giace il segmento [(0,0);(x,y)]
+forma con l'asse x di un sistema a coordinate cartesiane
+*/
+Math.atan(y / x);
+
+ +

Note that you may want to avoid using ±Infinity for stylistic reasons. In this case, {{jsxref("Math.atan2()")}} with 0 as the second argument may be a better solution.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.4', 'Math.atan')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.atan', 'Math.atan')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.atan', 'Math.atan')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.Math.atan")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/atan2/index.html b/files/it/web/javascript/reference/global_objects/math/atan2/index.html new file mode 100644 index 0000000000..842106f7a1 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/atan2/index.html @@ -0,0 +1,155 @@ +--- +title: Math.atan2() +slug: Web/JavaScript/Reference/Global_Objects/Math/atan2 +tags: + - Arcotangente + - JavaScript + - Math + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan2 +--- +
{{JSRef}}
+ +

La funzione Math.atan2() restituisce l'arcotangente del quoziente dei suoi argomenti.

+ +

Sintassi

+ +
Math.atan2(y, x)
+ +

Parametri

+ +
+
y
+
Primo numero.
+
x
+
Secondo numero.
+
+ +

Valore restituito

+ +

L'arcotangente del quoziente degli argomenti forniti alla funzione, espresso in radianti e compreso tra -π e π.

+ +

Descrizione

+ +

Il metodo Math.atan2() restituisce un valore compreso tra -π e π che reppresenta l'angolo teta di un punto (x, y). Questo angolo è orientato in senso antiorario, misurato in radianti e compreso tra l'asse positivo delle ascisse, ed il punto (x, y). È importante ricordare che il primo argomento da fornire alla funzione è l'ordinata del punto ed il secondo la sua ascissa.

+ +

A simple diagram showing the angle returned by atan2(y, x)

+ +

A Math.atan2() vengono passate x ed y separatamente, mentre a Math.atan() deve essere passato il loro quoziente.

+ +

Poichè atan2() è un metodo statico di Math esso viene sempre utilizzato nella forma Math.atan2(), invece che come metodo di un oggetto Math che hai personalmente creato (Math non è un costruttore).

+ +

Examples

+ +

Using Math.atan2()

+ +
Math.atan2(90, 15); // 1.4056476493802699
+Math.atan2(15, 90); // 0.16514867741462683
+
+Math.atan2(±0, -0);               // ±PI.
+Math.atan2(±0, +0);               // ±0.
+Math.atan2(±0, -x);               // ±PI con x > 0.
+Math.atan2(±0, x);                // ±0 con x > 0.
+Math.atan2(-y, ±0);               // -PI/2 con y > 0.
+Math.atan2(y, ±0);                // PI/2 con y > 0.
+Math.atan2(±y, -Infinity);        // ±PI con y finito e y > 0.
+Math.atan2(±y, +Infinity);        // ±0 con y finito e y > 0.
+Math.atan2(±Infinity, x);         // ±PI/2 con x finito.
+Math.atan2(±Infinity, -Infinity); // ±3*PI/4.
+Math.atan2(±Infinity, +Infinity); // ±PI/4.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.5', 'Math.atan2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.atan2', 'Math.atan2')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.atan2', 'Math.atan2')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

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

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/ceil/index.html b/files/it/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..c8cdcb96dd --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,161 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +
{{JSRef}}
+ +

La funzione Math.ceil() ritorna il più piccolo intero più grande di o uguale a un dato numero.

+ +

Sintassi

+ +
Math.ceil(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

Il più piccolo intero più grande di o uguale al dato numero.

+ +

Descrizione

+ +

Visto che ceil() è un metodo statico di Math, va usato sempre come Math.ceil(), piuttosto che come metodo di un oggetto Math creato (Math non è un costruttore).

+ +

Esempi

+ +

Usare Math.ceil()

+ +

L'esempio seguente mostra un uso di Math.ceil().

+ +
Math.ceil(.95);    // 1
+Math.ceil(4);      // 4
+Math.ceil(7.004);  // 8
+Math.ceil(-0.95);  // -0
+Math.ceil(-4);     // -4
+Math.ceil(-7.004); // -7
+
+ +

Arrotondamento decimale

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei browser

+ + + +

{{Compat("javascript.builtins.Math.ceil")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/e/index.html b/files/it/web/javascript/reference/global_objects/math/e/index.html new file mode 100644 index 0000000000..859d16145b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,79 @@ +--- +title: Math.E +slug: Web/JavaScript/Reference/Global_Objects/Math/E +translation_of: Web/JavaScript/Reference/Global_Objects/Math/E +--- +
{{JSRef}}
+ +

La costante Math.E rappresenta la base del logaritmo naturale, e, equivale approssimativamente a 2.718.

+ +

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

+ +
{{EmbedInteractiveExample("pages/js/math-e.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrizione

+ +

Poiché E è una proprietà statica di Math, lo si usa sempre come Math.E, piuttosto che come un metodo di un Oggetto Math appositamente creato (Math non ha un costruttore).

+ +

Esempi

+ +

Uso di Math.E

+ +

Il codice seguente restitusice e:

+ +
function getNapier() {
+  return Math.E;
+}
+
+getNapier(); // 2.718281828459045
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Math.E")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/floor/index.html b/files/it/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..3f7f6c7851 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,158 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +
{{JSRef}}
+ +

La funzione Math.floor() restituisce il numero intero, arrotondato per difetto, del numero passato come parametro.

+ +

Sintassi

+ +
Math.floor(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

Un numero intero rappresentante l'arrotondamento per difetto del numero passato come parametro.

+ +

Descrizione

+ +

Siccome floor() è un metodo statico di Math, viene sempre usato come Math.floor() piuttosto che come metodo di un oggetto Math creato in precedenza (Math non è un costruttore).

+ +

Esempi

+ +

Math.floor()

+ +
Math.floor( 45.95); //  45
+Math.floor( 45.05); //  45
+Math.floor(  4   ); //   4
+Math.floor(-45.05); // -46
+Math.floor(-45.95); // -46
+
+ +

Arrotondamento decimale

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei Browser

+ + + +

{{Compat("javascript.builtins.Math.floor")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/index.html b/files/it/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..69cd2ec012 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,208 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math è un oggetto precostruito che possiede proprietà e metodi per restituire i risultati di costanti e funzioni matematiche. Math non è una funzione.

+ +

Descrizione

+ +

Diversamente dagli altri oggetti globali, Math non è un costruttore. Tutte le proprietà e i metodi di Math sono statici. Per riferirsi alla costante Pi si usa  Math.PI e per chiamare la funzione Seno si usa Math.sin(x) , dove x è l'argomento del metodo. Le costanti sono definite con la piena precisione dei numeri reali in JavaScript.

+ +

Proprietà

+ +
+
{{jsxref("Math.E")}}
+
Costante di Eulero e base dei logaritmi naturali, approssimativamente 2.718.
+
{{jsxref("Math.LN2")}}
+
Logaritmo naturale di 2, approssimativamente 0.693.
+
{{jsxref("Math.LN10")}}
+
Logaritmo naturale di 10, approssimativamente 0.693.
+
{{jsxref("Math.LOG2E")}}
+
Logaritmo a base 2 di E, approssimativamente 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Logaritmo a base 10 di E, approssimativamente 1.443.
+
{{jsxref("Math.PI")}}
+
Rapporto tra la circonferenza di un cerchio ed il suo diametro, approssimativamente 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Radice quadrata di 1/2  ; equivale a 1 fratto la radice quadrata di 2, approsimativamente  0.707.
+
{{jsxref("Math.SQRT2")}}
+
Radice quadrata di 2, approssimativamente 1.414.
+
+ +

Metodi

+ +
+

Ricorda che le funzioni trigonometriche (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) si aspettano e restituiscono gli angoli in radianti. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

+
+ +
+

Ricorda che la precisione di molte delle funzioni matematiche è dipendente dall'sistema di implementazione. questo significa che browser differenti possono dare risultati diversi, e anche lo stessomotore JS su un differente sistema operativo o architettura può dare risultati discordi.

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Returns the absolute value of a number.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Returns the arccosine of a number.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Returns the hyperbolic arccosine of a number.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Returns the arcsine of a number.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Returns the hyperbolic arcsine of a number.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Returns the arctangent of a number.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Returns the hyperbolic arctangent of a number.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Returns the arctangent of the quotient of its arguments.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
Returns the cube root of a number.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Returns the smallest integer greater than or equal to a number.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Returns the number of leading zeroes of a 32-bit integer.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Returns the cosine of a number.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Returns the hyperbolic cosine of a number.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
Returns subtracting 1 from exp(x).
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Returns the largest integer less than or equal to a number.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Returns the nearest single precision float representation of a number.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
Returns the square root of the sum of squares of its arguments.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Returns the result of a 32-bit integer multiplication.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Returns the natural logarithm (loge, also ln) of a number.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
Returns the natural logarithm of 1 + x (loge, also ln) of a number.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
Returns the base 10 logarithm of a number.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
Returns the base 2 logarithm of a number.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
Returns the largest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
Returns the smallest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
Returns base to the exponent power, that is, baseexponent.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Returns a pseudo-random number between 0 and 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Returns the value of a number rounded to the nearest integer.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
Returns the sign of the x, indicating whether x is positive, negative or zero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Returns the sine of a number.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Returns the hyperbolic sine of a number.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Returns the positive square root of a number.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Returns the tangent of a number.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Returns the hyperbolic tangent of a number.
+
Math.toSource() {{non-standard_inline}}
+
Returns the string "Math".
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Returns the integral part of the number x, removing any fractional digits.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

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

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/max/index.html b/files/it/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..1c7f425fd0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,145 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - JavaScript + - Math + - Referenza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +
{{JSRef}}
+ +

La funzione Math.max() restituisce il massimo tra zero o più numeri.

+ +

Sintassi

+ +
Math.max([valore1[, valore2[, ...]]])
+ +

Parametri

+ +
+
valore1, valore2, ...
+
Numeri.
+
+ +

Descrizione

+ +

Dato che max() è un metodo statico di Math, viene solitamente usato tramite Math.max(), piuttosto che come metodo di un oggetto di tipo Math (Math non è un construttore).

+ +

Se non vengono passati parametri, il risultato è -{{jsxref("Infinity")}}.

+ +

Se anche solo uno dei parametri non può essere convertito a numero, il risultato è {{jsxref("NaN")}}.

+ +

Esempi

+ +

Usando Math.max()

+ +
Math.max(10, 20);   //  20
+Math.max(-10, -20); // -10
+Math.max(-10, 20);  //  20
+
+ +

La seguente funzione usa il metodo {{jsxref("Function.prototype.apply()")}} per trovare l'elemento massimo in un array di numeri. 
+ getMaxOfArray([1, 2, 3]) è equivalente a Math.max(1, 2, 3) ma può essere usata con array di qualunque dimensione creati programmaticamente.

+ +
function getMaxOfArray(numArray) {
+  return Math.max.apply(null, numArray);
+}
+
+ +

Con il nuovo {{jsxref("Operators/Spread_operator", "spread operator")}}, ottenere l'elemento massimo di un array è ancora più semplice.

+ +
var arr = [1, 2, 3];
+var max = Math.max(...arr);
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi inoltre

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/min/index.html b/files/it/web/javascript/reference/global_objects/math/min/index.html new file mode 100644 index 0000000000..562292e15b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,160 @@ +--- +title: Math.min() +slug: Web/JavaScript/Reference/Global_Objects/Math/min +tags: + - JavaScript + - Matemática + - Math + - Minimo + - Più grande + - Più piccolo + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/min +--- +

 

+ +
{{JSRef}}
+ +

La funzione  Math.min() ritorna il più piccolo tra zero o più numeri.

+ +

Sintassi

+ +
Math.min([value1[, value2[, ...]]])
+ +

Parametri

+ +
+
value1, value2, ...
+
numeri.
+
+ +

Valori di Ritorno

+ +

Il più piccolo dei valori dati in input. Se uno degli argomenti non può essere convertito in numero, viene ritornato {{jsxref("NaN")}}.

+ +

Descrizione

+ +

Siccome min() è un metodo static di Math , lo si può sempre usare come Math.min(), piuttosto che come un metodo di un oggetto istanza di Math da te creato (Math non possiede costruttori).

+ +

Se non sono dati argomenti allora il metodo restituirà {{jsxref("Infinity")}}.

+ +

Se anche uno degli aromenti non può essere convertito in un numero, il risultato sarà {{jsxref("NaN")}}.

+ +

Esempi

+ +

Usando Math.min()

+ +

L'sempio di seguito assegna a z il valore minore tra  x e y:

+ +
var x = 10, y = -20;
+var z = Math.min(x, y);
+
+ +

Ritagliare un valore con Math.min()

+ +

Math.min() è spesso usato per limitare un valore in modo che sia sempre minore o uguale a un certo valore limite.
+ Ad esempio il seguente codice

+ +
var x = f(foo);
+
+if (x > boundary) {
+  x = boundary;
+}
+
+ +

può essere scritto come

+ +
var x = Math.min(f(foo), boundary);
+
+ +

{{jsxref("Math.max()")}} può essere similmente utilizzato per limitare il valore massimo.

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementato in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
+ +

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

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/pow/index.html b/files/it/web/javascript/reference/global_objects/math/pow/index.html new file mode 100644 index 0000000000..5db4139f6a --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,151 @@ +--- +title: Math.pow() +slug: Web/JavaScript/Reference/Global_Objects/Math/pow +translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow +--- +
{{JSRef}}
+ +

La funzione Math.pow() restituisce la potenza della base che si desidera moltiplicare per se stessa a seconda del valore dell'esponenete, cioè baseesponente.

+ +

Sintassi

+ +
Math.pow(base, esponente)
+ +

Parametri

+ +
+
base
+
La basee del numero.
+
esponente
+
L'esponente usato per elevare la base.
+
+ +

Valore di Ritorno

+ +

Un numero che rappresenta la base elevata alla potenza dell'esponente.

+ +

Descrizione

+ +

Siccome pow()  è un metodo static di Math, lo usi sempre nella forma Math.pow(), piuttosto che come un metodo di un oggetto Math da te creato (Math non ha costruttori).

+ +

Esempi

+ +

Usando Math.pow()

+ +
// semplice
+Math.pow(7, 2);    // 49
+Math.pow(7, 3);    // 343
+Math.pow(2, 10);   // 1024
+// esponenti fratti
+Math.pow(4, 0.5);  // 2 (radice quadrata di 4)
+Math.pow(8, 1/3);  // 2 (radice cubica di 8)
+Math.pow(2, 0.5);  // 1.4142135623730951 (radice quadrata di 2)
+Math.pow(2, 1/3);  // 1.2599210498948732 (radice cubica di 2)
+// esponenti negativi
+Math.pow(7, -2);   // 0.02040816326530612 (1/49)
+Math.pow(8, -1/3); // 0.5
+// basi negative
+Math.pow(-7, 2);   // 49 (i quadrati son sempre positivi)
+Math.pow(-7, 3);   // -343 (i cubi possono essere negativi)
+Math.pow(-7, 0.5); // NaN (i numeri negativi non hanno una quadrata reale)
+// Siccome le radici "pari" e quelle "dispari" sono vicine tra loro,
+// e i limiti della precisione numerica per i valori di tipo float,
+// le basi negative con esponenti fratti ritornano sempre NaN
+Math.pow(-7, 1/3); // NaN
+
+ +

Specifiche Tecniche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioneStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definizione iniziale. Implementata in  JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.2.13', 'Math.pow')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.pow', 'Math.pow')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.pow', 'Math.pow')}}{{Spec2('ESDraft')}} 
+ +

Compatiblità 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}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/random/index.html b/files/it/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..3fcd849257 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,107 @@ +--- +title: Math.random() +slug: Web/JavaScript/Reference/Global_Objects/Math/random +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +
{{JSRef}}
+ +
La funzione Math.random()  ritorna un numero pseudo-casuale in virgola mobile compreso tra 0 e 1, con 0 incluso e 1 escluso (quindi nell'intervallo [0, 1)), scalabile al range desiderato. L'implementazione seleziona un numero (seme) iniziale utile all'algoritmo di generazione per restituire numeri randomici, il quale non può essere scelto o resettato dall'utente.
+ +
 
+ +
+

Math.random() non permette la generazione crittograficamente sicura dei numeri casuali, di conseguenza è altamente sconsigliato il suo impiego nell'ambito della sicurezza. Piuttosto sarebbe più corretto utilizzare la Web Crypto API instead, e più precisamente il metodo {{domxref("RandomSource.getRandomValues()", "window.crypto.getRandomValues()")}}.

+
+ +

Sintassi

+ +
Math.random()
+ +

Valore di ritorno

+ +

Un numero pseudo casuale in virgola mobile compreso tra 0 (incluso) e 1 (escluso).

+ +

Esempi

+ +

Bisogna notare che dal momento che i numeri in virgola mobile di JavaScript seguono lo standard IEEE 754 che arrotonda i numeri al numero pari più vicino, i range mostrati per la funzione sottostante non sono esatti (escludendo quello per Math.random()). Se si scelgono margini molto elevati (dell'ordine di 253  o più) è possibile, in casi estremamente rari, calcolare il limite superiore solitamente escluso.

+ +

Ottenere un numero tra [0, 1)

+ +
function getRandom() {
+  return Math.random();
+}
+
+ +

Ottenere un numero random tra due valori

+ +

Questo esempio restituisce un numero random tra due valori specificati. Il valore non è minore di (e può essere uguale a) min, nè maggiore (e nè uguale) a max. 

+ +
function getRandomArbitrary(min, max) {
+  return Math.random() * (max - min) + min;
+}
+
+ +

Ottenere un intero random tra due valori

+ +

Questo esempio restituisce un intero random tra due valori specificati. Il valore non è minore di min (oppure l'intero più grande di min se quest'ultimo non è un intero), nè maggiore (nè uguale) a max. 

+ +
function getRandomInt(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min)) + min; //Il max è escluso e il min è incluso
+}
+
+ +
+

Si potrebbe utilizzare l'arrotondamento per ottenere questo, tuttavia così facendo i numeri casuali seguirebbero una distribuzione non uniforme, magari non accettabile.

+
+ +

Ottenere un intero random tra due valori con estremi inclusi

+ +

Le funzioni viste finora escludono sempre l'estremo superiore del range scelto. La funzione getRandomIntInclusive() descritta sotto permette di ottenere questo.

+ +
function getRandomIntInclusive(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min + 1)) + min; //Il max è incluso e il min è incluso
+}
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. JS 1.0 (solo per UNIX) / JS 1.1. (tutte le piattaforme)
{{SpecName('ES5.1', '#sec-15.8.2.14', 'Math.random')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.random', 'Math.random')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.random', 'Math.random')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ + + +

{{Compat("javascript.builtins.Math.random")}}

+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/math/round/index.html b/files/it/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..4b20fb4a42 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,100 @@ +--- +title: Math.round() +slug: Web/JavaScript/Reference/Global_Objects/Math/round +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +
{{JSRef}}
+ +

La funzione Math.round() restituisce il valore di un numero approssimato all'intero ad esso più vicino.

+ +
{{EmbedInteractiveExample("pages/js/math-round.html")}}
+ + + +

Sintassi

+ +
Math.round(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore restituito

+ +

Il valore del numero dato approssimato all'intero più vicino.

+ +

Descrizione

+ +

Se la parte frazionale del numero è maggiore di 0.5, l'argomento (x) è approssimato all'intero successivo con il valore assoluto più elevato. Se è inferiore di 0.5, l'argomento è approssimato all'intero con il valore assoluto più basso.  Se la parte frazionale è esattamente 0.5, l'argomento è approssimato all'intero successivo nella direzione di +∞.  Si noti che questo è diverso da quanto accade nelle funzioni round() di molti altri linguaggi, che spesso invece approssimano questo caso all'intero successivo più lontano da zero, (dando un risultato diverso nel caso dei numeri negativi con una parte frazionale di esattamente 0.5).

+ +

Poiché round() è un metodo statico di Math, lo si usa sempre come Math.round(), piuttosto che come un metodo di un Oggetto Math appositamente creato (Math non ha un costruttore).

+ +

Esempi

+ +
Math.round( 20.49); //  20
+Math.round( 20.5 ); //  21
+Math.round( 42   ); //  42
+Math.round(-20.5 ); // -20
+Math.round(-20.51); // -21
+
+ +

 

+ +

Specifications

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.round', 'Math.round')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.round', 'Math.round')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.round")}}

+ +

 

+ +

See also

+ +

 

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/sqrt/index.html b/files/it/web/javascript/reference/global_objects/math/sqrt/index.html new file mode 100644 index 0000000000..6daf577e02 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/sqrt/index.html @@ -0,0 +1,136 @@ +--- +title: Math.sqrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt +--- +
{{JSRef}}
+ +

La funzione Math.sqrt() ritorna la radice quadrata di un numero, cioè :

+ +

x0,Math.sqrt(x)=x=the uniquey0such thaty2=x\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{l'unico} \; y \geq 0 \; \text{tale che} \; y^2 = x

+ +

Sintassi

+ +
Math.sqrt(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

La radice quadrata di un dato numero. Se il numero è negativo viene ritornato {{jsxref("NaN")}}.

+ +

Descrizione

+ +

Se il segno di x è negativo, Math.sqrt() ritorna {{jsxref("NaN")}}.

+ +

Siccome sqrt() è un metodo static di Math, puoi usarlo sempre come Math.sqrt(), piutttosto che come un metodo di un oggetto di tipo Math creato da te (Math non è un costruttore).

+ +

Esempio

+ +

Uso di Math.sqrt()

+ +
Math.sqrt(9); // 3
+Math.sqrt(2); // 1.414213562373095
+
+Math.sqrt(1);  // 1
+Math.sqrt(0);  // 0
+Math.sqrt(-1); // NaN
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementato per JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.17', 'Math.sqrt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ESDraft')}} 
+ +

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

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/nan/index.html b/files/it/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..992f063e9d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,79 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La proprietà globale NaN è un valore che rappresenta un non numero (Not-a-Number).

+ +

{{js_property_attributes(0,0,0)}}

+ +

Sintassi

+ +
NaN
+ +

Descrizione

+ +

Nan è una proprietà del global object e indica il fatto che un certo valore non è un numero legale/valido.

+ +

Il valore iniziale di Nan è Not-A-Number — lo stesso valore che si può riscontrare accedendo a Number.NaN. Nei browser moderni NaN è una proprietà non configurabile e non scrivibile (read-only).

+ +

NaN è restituito principalmente come valore di fallimento dalle funzioni "matematiche" come Math.sqrt(-1) oppure quando si prova ad eseguire il parseInt di una stringa che non contiene cifre numeriche come parseInt("blabla")

+ +

Testare il valore NaN

+ +

Gli operatori di uguaglianza (== o ===) non possono essere usati per verificare il valore di NaN. Deve essere invece utilizzato il metodo IsNaN() presente sia nell'oggetto globale {{jsxref("Global_Objects/isNaN", "isNaN()")}} che nell'oggetto Number {{jsxref("Number.isNaN()")}}.  

+ +
NaN === NaN;        // false
+Number.NaN === NaN; // false
+isNaN(NaN);         // true
+isNaN(Number.NaN);  // true
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.1', 'NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}{{Spec2('ES6')}} 
+ +

Compatibilità

+ + + +

{{Compat("javascript.builtins.NaN")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/null/index.html b/files/it/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..80ee3de685 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,89 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +
{{jsSidebar("Objects")}}
+ +

Il valore null rappresenta l'assenza intenzionale di qualsiasi valore dell'oggetto. È una delle {{Glossary("Primitive", "primitive values")}} di JavaScript.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-null.html")}}
+ + + +

Sintassi

+ +
null
+ +

Descrizione

+ +

Il valore null è scritto con un letterale: null. null non è un identificatore per una proprietà dell'oggetto globale, come {{jsxref("Global_Objects/undefined","undefined")}} può essere. Invece, null esprime una mancanza di identificazione, indicando che una variabile punta a nessun oggetto. Nelle API, null viene spesso recuperato in un punto in cui è possibile prevedere un oggetto ma nessun oggetto è rilevante.

+ +
// foo non esiste Non è definito e non è mai stato inizializzato:
+foo;
+"ReferenceError: foo is not defined"
+
+// foo è noto per esistere ora ma non ha alcun tipo o valore:
+var foo = null;
+foo;
+"null"
+
+ +

Differenze tra nullundefined

+ +

Durante il controllo per nullundefined, attenti alle differenze tra gli operatori equality (==) e identity (===), come il primo esegue la conversione del tipo.

+ +
typeof null          // "object" (non "null" per motivi legacy)
+typeof undefined     // "undefined"
+null === undefined   // false
+null  == undefined   // true
+null === null        // true
+null == null         // true
+!null                // true
+isNaN(1 + null)      // false
+isNaN(1 + undefined) // true
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-null-value', 'null value')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-null-value', 'null value')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.null")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/number/index.html b/files/it/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..39c8eb37d2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,188 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
    +
  1. {{JSRef}}
  2. +
+ +
Number is a primitive wrapper object used to represent and manipulate numbers like 37 or -9.25.
+ +
+ +
+ +

The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.

+ +

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding. The largest value a Number can hold is about 1.8×10308. Numbers beyond that are replaced with the special Number constant {{jsxref("Infinity")}}.

+ +

A number literal like 37 in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript now has a {{jsxref("BigInt")}} type, but it was not designed to replace Number for everyday uses. 37 is still a Number, not a BigInt.)

+ +
+
+ +

Description

+ +

When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns {{jsxref("NaN")}}.

+ +

Literal syntax

+ +
123    // one-hundred twenty-three
+123.0  // same
+123 === 123.0  // true
+ +

Function syntax

+ +
Number('123')  // returns the number 123
+Number('123') === 123  // true
+
+Number("unicorn")  // NaN
+Number(undefined)  // NaN
+
+ +

Constructor

+ +
+
Number()
+
Creates a new Number value.
+
+ +

Static properties

+ +
+
{{jsxref("Number.EPSILON")}}
+
The smallest interval between two representable numbers.
+
{{jsxref("Number.MAX_SAFE_INTEGER")}}
+
The maximum safe integer in JavaScript (253 - 1).
+
{{jsxref("Number.MAX_VALUE")}}
+
The largest positive representable number.
+
{{jsxref("Number.MIN_SAFE_INTEGER")}}
+
The minimum safe integer in JavaScript (-(253 - 1)).
+
{{jsxref("Number.MIN_VALUE")}}
+
The smallest positive representable number—that is, the positive number closest to zero (without actually being zero).
+
{{jsxref("Number.NaN")}}
+
Special "Not a Number" value.
+
{{jsxref("Number.NEGATIVE_INFINITY")}}
+
Special value representing negative infinity. Returned on overflow.
+
{{jsxref("Number.POSITIVE_INFINITY")}}
+
Special value representing infinity. Returned on overflow.
+
{{jsxref("Number.prototype")}}
+
Allows the addition of properties to the Number object.
+
+ +

Static methods

+ +
+
{{jsxref("Number.isNaN()")}}
+
Determine whether the passed value is NaN.
+
{{jsxref("Number.isFinite()")}}
+
Determine whether the passed value is a finite number.
+
{{jsxref("Number.isInteger()")}}
+
Determine whether the passed value is an integer.
+
{{jsxref("Number.isSafeInteger()")}}
+
Determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1).
+
{{jsxref("Number.parseFloat()", "Number.parseFloat(string)")}}
+
This is the same as the global {{jsxref("parseFloat", "parseFloat()")}} function.
+
{{jsxref("Number.parseInt()", "Number.parseInt(string, [radix])")}}
+
This is the same as the global {{jsxref("parseInt", "parseInt()")}} function.
+
+ +

Instance methods

+ +
+
{{jsxref("Number.prototype.toExponential()" ,"Number.prototype.toExponential(fractionDigits)")}}
+
Returns a string representing the number in exponential notation.
+
{{jsxref("Number.prototype.toFixed()", "Number.prototype.toFixed(digits)")}}
+
Returns a string representing the number in fixed-point notation.
+
{{jsxref("Number.prototype.toLocaleString()", "Number.prototype.toLocaleString([locales [, options]])")}}
+
Returns a string with a language sensitive representation of this number. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
+
{{jsxref("Number.prototype.toPrecision()", "Number.prototype.toPrecision(precision)")}}
+
Returns a string representing the number to a specified precision in fixed-point or exponential notation.
+
{{jsxref("Number.prototype.toString()", "Number.prototype.toString([radix])")}}
+
Returns a string representing the specified object in the specified radix ("base"). Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("Number.prototype.valueOf()")}}
+
Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
+
+ +

Examples

+ +

Using the Number object to assign values to numeric variables

+ +

The following example uses the Number object's properties to assign values to several numeric variables:

+ +
const biggestNum     = Number.MAX_VALUE
+const smallestNum    = Number.MIN_VALUE
+const infiniteNum    = Number.POSITIVE_INFINITY
+const negInfiniteNum = Number.NEGATIVE_INFINITY
+const notANum        = Number.NaN
+
+ +

Integer range for Number

+ +

The following example shows the minimum and maximum integer values that can be represented as Number object. (More details on this are described in the ECMAScript standard, chapter 6.1.6 The Number Type.)

+ +
const biggestInt  = Number.MAX_SAFE_INTEGER  //  (253 - 1) =>  9007199254740991
+const smallestInt = Number.MIN_SAFE_INTEGER  // -(253 - 1) => -9007199254740991
+ +

When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them to Number type.

+ +

A possible workaround is to use {{jsxref("String")}} instead.

+ +

Larger numbers can be represented using the {{jsxref("BigInt")}} type.

+ +

Using Number to convert a Date object

+ +

The following example converts the {{jsxref("Date")}} object to a numerical value using Number as a function:

+ +
let d = new Date('December 17, 1995 03:24:00')
+console.log(Number(d))
+
+ +

This logs 819199440000.

+ +

Convert numeric strings and null to numbers

+ +
Number('123')     // 123
+Number('123') === 123 /// true
+Number('12.3')    // 12.3
+Number('12.00')   // 12
+Number('123e-1')  // 12.3
+Number('')        // 0
+Number(null)      // 0
+Number('0x11')    // 17
+Number('0b11')    // 3
+Number('0o11')    // 9
+Number('foo')     // NaN
+Number('100a')    // NaN
+Number('-Infinity') //-Infinity
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Number")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/assign/index.html b/files/it/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..6280745df2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,268 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +
{{JSRef}}
+ +

Sommario

+ +

La funzione Object.assign() copia tutte le proprietà enumerabili da uno o più oggetti di origine in un oggetto di destinazione. Restituisce l'oggetto di destinazione.

+ +

Sintassi

+ +
Object.assign(target, ...sources)
+ +

Parametri

+ +
+
target
+
L'oggetto di destinazione.
+
sources
+
Gli oggetti di origine.
+
+ +

Descrizione

+ +

La funzione Object.assign() copia soltanto le proprietà enumerabili appartenenti agli oggetti di origine (non quelle che fanno parte della loro catena dei prototipi) in un oggetto di destinazione. Utilizza [[Get]] sugli oggetti di origine e [[Put]] su quello di destinazione, quindi invoca getter e setter, quando presenti. Quindi assegna le proprietà, piuttosto che limitarsi a copiarle o a definirne di nuove. Ciò lo rende inadatto per aggiungere nuove proprietà in un prototipo se le proprietà vengono copiate da un oggetto contenente getter o setter. Per copiare le proprietà, incluso il fatto di essere enumerabili o no, in un prototipo, bisognerebbe usare {{jsxref("Object.defineProperty()")}}.

+ +

Vengono copiate sia le proprietà aventi come nomi delle {{jsxref("String", "stringhe")}} che dei {{jsxref("Symbol", "simboli")}}.

+ +

In caso di errore, per esempio se una proprietà non è sovrascrivibile, viene generato un {{jsxref("TypeError")}}, e l'oggetto di destinazione rimane invariato.

+ +

Notare che Object.assign() non genera un errore se uno dei valori di origine è {{jsxref("null")}} o {{jsxref("undefined")}}.

+ +

Esempi

+ +

Clonare un oggetto

+ +

Si potrebbe pensare di clonare un oggetto semplicemente assegnandolo ad un altra variabile:

+ +
var obj = { a: 1 };
+var copia = obj;
+console.log(obj, copia); // { a: 1 }, { a: 1 }
+obj.a = 2;
+console.log(obj, copia); // { a: 2 }, { a: 2 }
+                         // Ma copia.a non valeva 1?
+ +

Utilizzando Object.assign() il problema non si verifica:

+ +
var obj = { a: 1 };
+var copia = Object.assign({}, obj);
+console.log(obj, copia); // { a: 1 }, { a: 1 }
+obj.a = 2;
+console.log(obj, copia); // { a: 2 }, { a: 1 }
+
+ +

Unire più oggetti

+ +
var o1 = { a: 1 };
+var o2 = { b: 2 };
+var o3 = { c: 3 };
+
+var obj = Object.assign(o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 }
+console.log(o1);  // { a: 1, b: 2, c: 3 }, le proprietà vengono aggiunte all'oggetto di destinazione
+
+ +

Copiare proprietà aventi come indici dei simboli

+ +
var o1 = { a: 1 };
+var o2 = { [Symbol("foo")]: 2 };
+
+var obj = Object.assign({}, o1, o2);
+console.log(obj); // { a: 1, Symbol(foo): 2 }
+
+ +

Le proprietà ereditate o non-enumerabili non vengono copiate

+ +
var obj = Object.create({ foo: 1 }, { // foo è una proprietà ereditata
+  bar: {
+    value: 2  // bar è una proprietà non-enumerabile
+  },
+  baz: {
+    value: 3,
+    enumerable: true  // baz è una proprietà enumerabile
+  }
+});
+
+var copia = Object.assign({}, obj);
+console.log(copia); // { baz: 3 }
+
+ +

I valori primitivi vengono trasformati in oggetti

+ +
var v1 = '123';
+var v2 = true;
+var v3 = 10;
+var v4 = Symbol("foo");
+
+var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// I valori primitivi vengono trasformati in oggetti, null e undefined ignorati.
+// Notare che solo le stringhe hanno proprietà enumerabili
+console.log(obj); // { "0": "1", "1": "2", "2": "3" }
+
+ +

Se viene generata un eccezione, la funzione si ferma

+ +
var destinazione = Object.defineProperty({}, 'foo', {
+  value: 1,
+  writeable: false
+}); // destinazione.foo non può essere modificata
+
+Object.assign(destinazione, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" is read-only
+// L'eccezione viene generata quando si modifica destinazione.foo
+
+console.log(destinazione.bar);  // 2, Il primo oggetto viene copiato correttamente
+console.log(destinazione.foo2); // 3, La prima proprietà del secondo oggetto viene copiata correttamente
+console.log(destinazione.foo);  // 1, L'eccezione viene generata qui
+console.log(destinazione.foo3); // undefined, la funzione ha già finto di copiare
+console.log(destinazione.baz);  // undefined, la funzione ha già finto di copiare
+
+ +

Copiare i getter

+ +
var obj = {
+  foo: 1,
+  get bar() {
+    return 2;
+  }
+};
+
+var copia = Object.assign({}, obj);
+console.log(copia);
+// { foo: 1, bar: 2 }, non viene copiato il getter obj.bar, ma il suo valore
+
+// Questa funzione copia mantenendo getter e setter
+function myAssign(target, ...sources) {
+  sources.forEach(source => {
+    Object.defineProperties(target, Object.keys(source).reduce((descriptors, key) => {
+      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+      return descriptors;
+    }, {}));
+  });
+  return target;
+}
+
+var copia = myAssign({}, obj);
+console.log(copia);
+// { foo:1, get bar() { return 2 } }
+
+ +

Polyfill

+ +

Questo polyfill non supporta i simboli (che comunque non sono supportati da ECMAScript 5):

+ +
if (!Object.assign) {
+  Object.defineProperty(Object, 'assign', {
+    enumerable: false,
+    configurable: true,
+    writable: true,
+    value: function(target, firstSource) {
+      'use strict';
+      if (target === undefined || target === null) {
+        throw new TypeError('Cannot convert first argument to object');
+      }
+
+      var to = Object(target);
+      for (var i = 1; i < arguments.length; i++) {
+        var nextSource = arguments[i];
+        if (nextSource === undefined || nextSource === null) {
+          continue;
+        }
+        nextSource = Object(nextSource);
+
+        var keysArray = Object.keys(Object(nextSource));
+        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
+          var nextKey = keysArray[nextIndex];
+          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
+          if (desc !== undefined && desc.enumerable) {
+            to[nextKey] = nextSource[nextKey];
+          }
+        }
+      }
+      return to;
+    }
+  });
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}Definizione iniziale.
+ +

Compatibilità con i browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatChrome("45")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatOpera("32")}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatNo}}{{CompatChrome("45")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/create/index.html b/files/it/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..d2b020b955 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,234 @@ +--- +title: Object.create() +slug: Web/JavaScript/Reference/Global_Objects/Object/create +tags: + - Creazione + - Oggetto + - Prototipo + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +
+ {{JSRef("Global_Objects", "Object")}}
+

Sommario

+

Il metodo Object.create() crea un nuovo oggetto a partire dall'oggetto prototipo e dalle proprietà specificati.

+

Sintassi

+
Object.create(proto[, propertiesObject])
+

Parametri

+
+
+ proto
+
+ L'oggetto che farà da prototipo per il nuovo oggetto creato.
+
+ propertiesObject
+
+ Opzionale. Se specificato e non {{jsxref("Global_Objects/undefined", "undefined")}}, un oggetto le cui proprie proprietà enumerabili (ovvero, quelle proprietà definite esclusivamente su di sé e non quelle enumerabili presenti nella sua catena dei prototipi) specificano descrittori di proprietà da aggiungere all'oggetto appena creato, con i corrispondenti nomi di proprietà. Queste proprietà corrispondono al secondo argomento di {{jsxref("Object.defineProperties()")}}.
+
+

Throws

+

Lancia un'eccezione di tipo {{jsxref("Global_Objects/TypeError", "TypeError")}} se il parametro  proto non è {{jsxref("Global_Objects/null", "null")}} oppure un oggetto.

+

Esempi

+

Esempio: ereditarietà classica con Object.create

+

Sotto, trovi un esempio di come implementare un'ereditarietà classica usando Object.create. Si tratta di un'ereditarietà singola, l'unica supportata da Javascript.

+
// Shape - superclass
+function Shape() {
+  this.x = 0;
+  this.y = 0;
+}
+
+// superclass method
+Shape.prototype.move = function(x, y) {
+  this.x += x;
+  this.y += y;
+  console.info('Shape moved.');
+};
+
+// Rectangle - subclass
+function Rectangle() {
+  Shape.call(this); // call super constructor.
+}
+
+// subclass extends superclass
+Rectangle.prototype = Object.create(Shape.prototype);
+Rectangle.prototype.constructor = Rectangle;
+
+var rect = new Rectangle();
+
+console.log("Is rect an instance of Rectangle? " + (rect instanceof Rectangle)); // true
+console.log("Is rect an instance of Shape? " + (rect instanceof Shape)); // true
+
+rect.move(1, 1); // Outputs, 'Shape moved.'
+
+

Se desideri ereditare proprietà e metodi da oggetti multipli, puoi utilizzare dei mixins.

+
function MyClass() {
+  SuperClass.call(this);
+  OtherSuperClass.call(this);
+}
+
+MyClass.prototype = Object.create(SuperClass.prototype); // inherit
+mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin
+
+MyClass.prototype.myMethod = function() {
+  // do a thing
+};
+
+

La funzione mixin copia le funzioni dell'oggetto prototype della superclasse nell'oggetto prototype della sottoclasse; la funzione mixin deve essere implementata dall'utente. Un esempio di funzione simil mixin potrebbe essere jQuery.extend.

+

Esempio: Usare l'argomento propertiesObject con Object.create

+
var o;
+
+// create an object with null as prototype
+o = Object.create(null);
+
+
+o = {};
+// is equivalent to:
+o = Object.create(Object.prototype);
+
+
+// Example where we create an object with a couple of sample properties.
+// (Note that the second parameter maps keys to *property descriptors*.)
+o = Object.create(Object.prototype, {
+  // foo is a regular 'value property'
+  foo: { writable: true, configurable: true, value: 'hello' },
+  // bar is a getter-and-setter (accessor) property
+  bar: {
+    configurable: false,
+    get: function() { return 10; },
+    set: function(value) { console.log('Setting `o.bar` to', value); }
+  }
+});
+
+
+function Constructor() {}
+o = new Constructor();
+// is equivalent to:
+o = Object.create(Constructor.prototype);
+// Of course, if there is actual initialization code in the
+// Constructor function, the Object.create cannot reflect it
+
+
+// create a new object whose prototype is a new, empty object
+// and a adding single property 'p', with value 42
+o = Object.create({}, { p: { value: 42 } });
+
+// by default properties ARE NOT writable, enumerable or configurable:
+o.p = 24;
+o.p;
+// 42
+
+o.q = 12;
+for (var prop in o) {
+  console.log(prop);
+}
+// 'q'
+
+delete o.p;
+// false
+
+// to specify an ES3 property
+o2 = Object.create({}, {
+  p: {
+    value: 42,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  }
+});
+
+

Polyfill

+

Questo polyfill implementa il caso di utilizzo principale, ovvero creare un nuovo oggetto specificando un oggetto prototipo, ma non prende in considerazione il secondo argomento dell'API orginale.

+
if (typeof Object.create != 'function') {
+  Object.create = (function() {
+    var Object = function() {};
+    return function (prototype) {
+      if (arguments.length > 1) {
+        throw Error('Second argument not supported');
+      }
+      if (typeof prototype != 'object') {
+        throw TypeError('Argument must be an object');
+      }
+      Object.prototype = prototype;
+      var result = new Object();
+      Object.prototype = null;
+      return result;
+    };
+  })();
+}
+
+

Specifiche

+ + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.create', 'Object.create')}}{{Spec2('ES6')}} 
+

Compatibilità browser

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatChrome("5")}}{{CompatGeckoDesktop("2")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+
+ + + + + + + + + + + + + + + + + + + + + +
CaratteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatVersionUnknown}}{{CompatOperaMobile("11.50")}}{{CompatVersionUnknown}}
+
+

Basato sulla tabella di compatibilità di Kangax.

+

Vedi anche

+ diff --git a/files/it/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/it/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..c905420eb2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,224 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +
{{JSRef}}
+ +

Il metodo Object.defineProperties() definisce nuove proprietà o modifica le proprietà esistenti, direttamente sull'oggetto di ritorno.

+ +

Sintassi

+ +
Object.defineProperties(obj, props)
+ +

Parametri

+ +
+
obj
+
L'oggetto su cui definire le nuove proprietà o modificare le esistenti proprietà.
+
props
+
Un oggetto che contiene le proprietà enumerabili. Per ogni proprietà troviamo dei descrittori della proprietà stessa, che ne impostano il comportamento. Suddividiamo i descrittori in due tipologie: il data descriptors e i descrittorei che ne regolano gli accessi (guarda {{jsxref("Object.defineProperty()")}} per maggiori dettagli). I descrittori hanno le seguenti c:
+
+
+
configurable
+
true se e solo se la proprietà individuata dal descrittore può essere cambiata e se la proprietà può essere cancellata dal presente oggetto.
+ Defaults a false.
+
enumerable
+
true se e solo se la proprietà è visualizzabile durante una enumerazione delle proprietà del presente oggetto (es. for-in)
+ Defaults a false.
+
+ +
+
value
+
Il valore associato con la proprietà che si sta definendo. Può essere un qualsiasi valore valido di Javascript (number, object, function, ecc...)
+ Defaults a {{jsxref("undefined")}}.
+
writable
+
true se e solo se il valore associato per la proprietà può essere cambiato con un {{jsxref("Operators/Assignment_Operators", "operatore di assegnazione", "", 1)}}.
+ Defaults to false.
+
+ +
+
get
+
Una funzione che serve da getter (prelevare il dato) per la proprietà, o {{jsxref("undefined")}} se non è presente un getter. Il valore di ritorno della funzione verrà usato come valore della proprietà
+ Defaults a {{jsxref("undefined")}}.
+
set
+
Una funzione che serve da setter (impostare il dato) per la proprietà {{jsxref("undefined")}} se non è presente il setter. La funzione riceverà un solo argomento che verrà assegnato come valore della proprietà.
+ Defaults a {{jsxref("undefined")}}.
+
+
+
+ +

Valore di ritorno

+ +

L'oggetto che è stato passato alla funzione.

+ +

Descrizione

+ +

Object.defineProperties, in sostanza, definisce tutte le proprietà di un oggetto, corrispondenti alle proprietà "own" proprie di un oggetto obj.

+ +

Esempio

+ +
var obj = {};
+Object.defineProperties(obj, {
+  'property1': {
+    value: true,
+    writable: true
+  },
+  'property2': {
+    value: 'Hello',
+    writable: false
+  }
+  // etc. etc.
+});
+
+ +

Polyfill

+ +

Assumendo di eseguire un ambiente precedente con tutti i nomi e le proprietà che fanno riferimento ai valori iniziali, Object.defineProperties è quasi completamente equivalente (nota il commento in isCallable) al seguente reimplementazione in Javascript:

+ +
function defineProperties(obj, properties) {
+  function convertToDescriptor(desc) {
+    function hasProperty(obj, prop) {
+      return Object.prototype.hasOwnProperty.call(obj, prop);
+    }
+
+    function isCallable(v) {
+      // NB: modify as necessary if other values than functions are callable.
+      return typeof v === 'function';
+    }
+
+    if (typeof desc !== 'object' || desc === null)
+      throw new TypeError('bad desc');
+
+    var d = {};
+
+    if (hasProperty(desc, 'enumerable'))
+      d.enumerable = !!desc.enumerable;
+    if (hasProperty(desc, 'configurable'))
+      d.configurable = !!desc.configurable;
+    if (hasProperty(desc, 'value'))
+      d.value = desc.value;
+    if (hasProperty(desc, 'writable'))
+      d.writable = !!desc.writable;
+    if (hasProperty(desc, 'get')) {
+      var g = desc.get;
+
+      if (!isCallable(g) && typeof g !== 'undefined')
+        throw new TypeError('bad get');
+      d.get = g;
+    }
+    if (hasProperty(desc, 'set')) {
+      var s = desc.set;
+      if (!isCallable(s) && typeof s !== 'undefined')
+        throw new TypeError('bad set');
+      d.set = s;
+    }
+
+    if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d))
+      throw new TypeError('identity-confused descriptor');
+
+    return d;
+  }
+
+  if (typeof obj !== 'object' || obj === null)
+    throw new TypeError('bad obj');
+
+  properties = Object(properties);
+
+  var keys = Object.keys(properties);
+  var descs = [];
+
+  for (var i = 0; i < keys.length; i++)
+    descs.push([keys[i], convertToDescriptor(properties[keys[i]])]);
+
+  for (var i = 0; i < descs.length; i++)
+    Object.defineProperty(obj, descs[i][0], descs[i][1]);
+
+  return obj;
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/freeze/index.html b/files/it/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..26201fdb0c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,210 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +
{{JSRef}}
+ +

Il metodo Object.freeze() congela un oggetto: ne previene l'aggiunta, la modifica e la rimozione di proprietà, inclusa la loro enumerabilità, configurabilità e accessibilità. In sostanza, l'oggetto è reso effettivamente immutabile. Il metodo restituisce lo stesso oggetto che è stato passato alla funzione. 

+ +

Sintassi

+ +
Object.freeze(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da congelare.
+
+ +

Valore di ritorno

+ +

L'oggetto passato alla funzione.

+ +

Descrizione

+ +

Nulla può essere aggiunto o rimosso dall'insieme delle proprietà di un oggetto congelato. Qualsiasi tentativo di fare ciò fallirebbe, o silenziosamente o attraverso il ritorno di un errore {{jsxref("TypeError")}} (più frequentemente, ma non necessariamente, quest'ultimo scenario accadrebbe in {{jsxref("Strict_mode", "strict mode", "", 1)}}).

+ +

I valori delle proprietà non possono essere cambiati, anche quando si tratta di setters e getters. Da notare che se un oggetto costituisce il valore di una proprietà, esso può essere ancora modificato senza problemi, a meno che anch'esso non sia stato congelato.

+ +

Esempi

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// Nuove proprietà possono essere aggiunte, proprietà già esistenti possono
+// essere modificate o rimosse
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+
+// Sia l'oggetto che viene passato che quello restituito verranno congelati.
+// No serve salvare l'oggetto restituito per congelare l'originale
+var o = Object.freeze(obj);
+
+o === obj; // true
+Object.isFrozen(obj); // === true
+
+// Adesso qualsiasi cambiamento fallirà
+obj.foo = 'quux'; // silenziosamente, non succede niente
+obj.quaxxor = 'the friendly duck'; // silenziosamente, non aggiungerà alcuna proprietò
+
+
+// ...e nella modalità strict questi tentativi di modifica faranno lanciare TypeErrors
+function fail(){
+  'use strict';
+  obj.foo = 'sparky'; // throws a TypeError
+  delete obj.quaxxor; // throws a TypeError
+  obj.sparky = 'arf'; // throws a TypeError
+}
+
+fail();
+
+
+// Tentare di cambiare attraverso Object.defineProperty farà anche lanciare un TypeError
+Object.defineProperty(obj, 'ohai', { value: 17 }); // throws a TypeError
+Object.defineProperty(obj, 'foo', { value: 'eit' }); // throws a TypeError
+
+ +

Il seguente esempio mostra come oggetti che sono valori di proprietà possono essere mutati(il congelamento si ferma ad un solo livello di profondità).

+ +
obj1 = {
+  internal: {}
+};
+
+Object.freeze(obj1);
+obj1.internal.a = 'aValue';
+
+obj1.internal.a // 'aValue'
+
+
+// Per fare un oggetto totalmente non modificabile, congela ciascun oggetto in obj.
+// Per farlo noi usiamo questa funzione.
+function deepFreeze(obj) {
+
+  // Prende tutti i nomi delle proprietà definite in obj
+  var propNames = Object.getOwnPropertyNames(obj);
+
+  // Congela tutte le proprietà prima di congelare obj
+  propNames.forEach(function(name) {
+    var prop = obj[name];
+
+    // Congela prop se esso è un oggetto
+    if (typeof prop == 'object' && prop !== null)
+      deepFreeze(prop);
+  });
+
+  // Congela se stesso (niente operazione se esso è già congelato)
+  return Object.freeze(obj);
+}
+
+obj2 = {
+  internal: {}
+};
+
+deepFreeze(obj2);
+obj2.internal.a = 'anotherValue';
+obj2.internal.a; // undefined
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un oggetto, allora verrà ritornato un errore {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già congelato, e verrà perciò semplicemente ritornato.

+ +
> Object.freeze(1)
+TypeError: 1 is not an object // ES5 code
+
+> Object.freeze(1)
+1                             // ES2015 code
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}{{Spec2('ES5.1')}}Commento iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ESDraft')}}
+ +

Compatibilità con i browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Funzionalità di base{{CompatGeckoDesktop("2")}}{{CompatChrome("6")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Funzionalità di base{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..dd72c6cdf3 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,130 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +tags: + - ECMAScript5 + - ECMAScript6 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +
{{JSRef}}
+ +

Il metodo Object.getPrototypeOf() restituisce il prototipo (ovvero il valore della proprietà interna [[Prototype]]) dell'oggetto specificato.

+ +

Sintassi

+ +
Object.getPrototypeOf(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto di cui si vuole ottenere il prototipo.
+
+ +

Esempi

+ +
var proto = {};
+var obj = Object.create(proto);
+Object.getPrototypeOf(obj) === proto; // true
+
+ +

Note

+ +

Se il parametro obj non è un oggetto, nello standard ES5 il metodo innescherà un'eccezione {{jsxref("TypeError")}}, mentre nello standard ES6 il parametro sarà assegnato forzatamente ad un {{jsxref("Object")}}.

+ +
Object.getPrototypeOf("foo");
+// TypeError: "foo" is not an object (ES5 code)
+Object.getPrototypeOf("foo");
+// String.prototype                  (ES6 code)
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Prima definizione.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
+ +

Compatibilità fra i Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Note specifiche su Opera

+ +

Anche se le vecchie versioni di Opera non supportano ancora il metodo Object.getPrototypeOf(), comunque dalla versione 10.50 è stata implementata la proprietà non standard {{jsxref("Object.proto", "__proto__")}}.

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..7287ed1e18 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,164 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript + - Object + - Prototype + - hasOwnProperty + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +
{{JSRef}}
+ +

Il metodo hasOwnProperty() restituisce un valore booleano che indica se l'oggetto ha la proprietà specificata come propria proprietà (invece di ereditarla).

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-hasownproperty.html")}}
+ + + +

Sintassi

+ +
obj.hasOwnProperty(prop)
+ +

Parametri

+ +
+
prop
+
Il nome della {{jsxref("String")}} o il {{Glossary("Symbol")}} della proprietà da testare.
+
+ +

Valore di ritorno

+ +

Un {{jsxref("Boolean")}} che indica se l'oggetto ha o meno la proprietà specificata come proprietà propria.

+ +

Descrizione

+ +

Tutti i discendenti di {{jsxref("Object")}} ereditano il metodo hasOwnProperty. Questo metodo può essere utilizzato per determinare se un oggetto ha la proprietà specificata come proprietà diretta di tale oggetto; a differenza dell'operatore {{jsxref("Operators/in", "in")}}, questo metodo non controlla una proprietà nella catena di prototipi dell'oggetto.

+ +

Note

+ +

hasOwnProperty restituisce true anche se il valore della proprietà è nullundefined.

+ +
o = new Object();
+o.propOne = null;
+o.hasOwnProperty('propOne');   // ritorna true
+o.propTwo = undefined;
+o.hasOwnProperty('propTwo');   // ritorna true
+
+ +

Esempi

+ +

Usare hasOwnProperty per verificare l'esistenza di una proprietà

+ +

L'esempio seguente determina se l'oggetto o contiene una proprietà denominata prop:

+ +
o = new Object();
+o.hasOwnProperty('prop');   // ritorna false
+o.prop = 'exists';
+o.hasOwnProperty('prop');   // ritorna true
+
+ +

Dirette vs. proprietà ereditate

+ +

Il seguente esempio distingue tra proprietà dirette e proprietà ereditate attraverso la catena del prototipo:

+ +
o = new Object();
+o.prop = 'exists';
+o.hasOwnProperty('prop');             // ritorna true
+o.hasOwnProperty('toString');         // ritorna false
+o.hasOwnProperty('hasOwnProperty');   // ritorna false
+
+ +

Iterare sulle proprietà di un oggetto

+ +

L'esempio seguente mostra come eseguire iterazioni sulle proprietà di un oggetto senza eseguire l'esecuzione su proprietà ereditate. Si noti che il ciclo {{jsxref("Statements/for...in", "for...in")}} sta già solo iterando gli oggetti enumerabili, quindi non si dovrebbe assumere in base alla mancanza di proprietà non enumerabili mostrate nel ciclo che hasOwnProperty è strettamente limitato agli elementi enumerabili (come con {{jsxref("Object.getOwnPropertyNames()")}}).

+ +
var buz = {
+  fog: 'stack'
+};
+
+for (var name in buz) {
+  if (buz.hasOwnProperty(name)) {
+    console.log('this is fog (' +
+      name + ') for sure. Value: ' + buz[name]);
+  }
+  else {
+    console.log(name); // toString o qualcos'altro
+  }
+}
+
+ +

Usare hasOwnProperty come nome di una proprietà

+ +

JavaScript non protegge il nome della proprietà hasOwnProperty; quindi, se esiste la possibilità che un oggetto possa avere una proprietà con questo nome, è necessario utilizzare un hasOwnProperty esterno per ottenere risultati corretti:

+ +
var foo = {
+  hasOwnProperty: function() {
+    return false;
+  },
+  bar: 'Here be dragons'
+};
+
+foo.hasOwnProperty('bar'); // restituisce sempre false
+
+// Usare hasOwnProperty di un altro oggetto
+// e chiamarlo con 'this' impostato su foo
+({}).hasOwnProperty.call(foo, 'bar'); // true
+
+// È anche possibile utilizzare la proprietà hasOwnProperty
+// dal prototipo Object per questo scopo
+Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
+
+ +

Nota che nell'ultimo caso non ci sono oggetti appena creati.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ESDraft', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale Implementato in JavaScript 1.5.
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.Object.hasOwnProperty")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/index.html b/files/it/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..8c567d9ea2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,224 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsBrowserCompatibility + - NeedsMobileBrowserCompatibility + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Sommari

+ +

Il costruttore Object crea un oggetto.

+ +

Sintassi

+ +
// Letterale
+{ [ coppiaNomeValore1 [, coppiaNomeValore2 [, ...coppiaNomeValoreN] ] ] }
+
+// Richiamato come una classe
+new Object( [ value ] )
+ +

Parametri

+ +
+
coppiaNomeValore1, coppiaNomeValore2, ... coppiaNomeValoreN
+
Coppie formate da un nome (una stringa) e un valore (di qualsiasi tipo), dove il nome è separato dal valore con i due punti.
+
+
{
+    "nome1": "valore1",
+    nome2: "valore2" // Gli apici nel nome sono opzionali
+};
+
+
+
+ +
+
value
+
Qualsiasi valore.
+
+ +

Descrizione

+ +

Il costruttore Object crea un oggetto avente il valore dato. Se il valore è {{jsxref("Global_Objects/null", "null")}} o {{jsxref("Global_Objects/undefined", "undefined")}}, verrà creato un oggetto vuoto; altrimenti un oggetto del tipo corrispondente al valore dato. Se il valore è già un oggetto, verra restituito senza alcuna modifica.

+ +

Quando richiamato come normale funzione, il comportamento di Object() è identico a new Object().

+ +

Proprietà del costruttore Object

+ +
+
Object.length
+
Ha valore pari a 1.
+
{{jsxref("Object.prototype")}}
+
Permette di aggiungere altre proprietà ad ogni oggetto di tipo Object.
+
+ +

{{ jsOverrides("Function", "Properties", "prototype") }}

+ +

Metodi del costruttore Object

+ +
+
{{jsxref("Object.assign()")}} {{experimental_inline}}
+
Crea un nuovo oggetto copiando i valori di tutti le proprietà enumerabili da uno o più oggetti.
+
{{jsxref("Object.create()")}}
+
Crea un nuovo oggetto utilizzando il prototipo e le proprietà specificate.
+
{{jsxref("Object.defineProperty()")}}
+
Aggiunge una proprietà descritta dall'oggetto specificato.
+
{{jsxref("Object.defineProperties()")}}
+
Aggiunge più proprietà descritte dall'oggetto specificato.
+
{{jsxref("Object.freeze()")}}
+
Congela un oggetto: le sue proprietà non possono più essere cancellate o modificate.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Restituisce un oggetto che descriva la proprietà specificata.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Restituisce un array contenente i nomi di tutte le proprietà (enumerabili e non-enumerabili) dell'oggetto specificato.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Restituisce il prototipo dell'oggetto specificato.
+
{{jsxref("Object.is()")}} {{ experimental_inline() }}
+
Determina se due valori sono o no uguali (quindi lo stesso oggetto).
+
{{jsxref("Object.isExtensible()")}}
+
Determina se è permesso estendere un oggetto.
+
{{jsxref("Object.isFrozen()")}}
+
Determina se un oggetto è stato congelato.
+
{{jsxref("Object.isSealed()")}}
+
Determina se un oggetto è stato sigillato.
+
{{jsxref("Object.keys()")}}
+
Restituisce un array contenente i nomi di tutte le proprietà enumerabili dell'oggetto.
+
{{jsxref("Object.observe()")}} {{experimental_inline}}
+
Osserva i cambiamenti di un oggetto in modo asincrono.
+
{{jsxref("Object.preventExtensions()")}}
+
Impedisce ad un oggetto di essere esteso.
+
{{jsxref("Object.seal()")}}
+
Impedisce di eliminare le proprietà di un oggetto.
+
{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}
+
+

Imposta i prototipo (quindi la proprietà intena ​[[Prototype]]) di un oggetto.

+
+
+ +

{{jsOverrides("Function", "Methods", "create", "defineProperty", "defineProperties", "getOwnPropertyDescriptor", "getPrototypeOf")}}

+ +

Instanze di Object e l'oggetto prototipo Object

+ +

In JavaScript, tutti gli oggetti sono discendenti di Object; tutti gli oggetti ereditano metodi e proprietà di {{jsxref("Object.prototype")}}, anche se queste possono essere sovrascritte. Per esempio, i prototpipi degli altri costruttori sovrascrivono la proprietà constructor e forniscono un loro metodo toString(). I cambiamenti al prototipo di Object venogno estesi a tutti gli oggetti, eccetto quelli che sovrascrivono le proprietà e i metodi cambiati.

+ +

Poprietà

+ +

{{page('/it/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}

+ +

Metodi

+ +

{{page('/it/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}

+ +

Esempi

+ +

Usare Object con i valori null e undefined

+ +

Questi esempi restituiscono tutti lo stesso oggetto:

+ +
var o = {};
+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Usare Object per creare oggetti Boolean

+ +

I seguenti esempi assegnano alla variabile o un oggetto {{jsxref("Global_Objects/Boolean", "Boolean")}}:

+ +
var o = new Object(true);
+// Equivalente a new Boolean(true)
+ +
var o = new Object(Boolean());
+// Equivalente a new Boolean(false)
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition. Implemented in JavaScript 1.0StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/object/is/index.html b/files/it/web/javascript/reference/global_objects/object/is/index.html new file mode 100644 index 0000000000..ffb979fcb5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/is/index.html @@ -0,0 +1,130 @@ +--- +title: Object.is() +slug: Web/JavaScript/Reference/Global_Objects/Object/is +tags: + - Comparazione + - Condizionale + - Condizione + - ECMAScript 2015 + - Equalità + - Italiano + - JavaScript + - Oggetto + - Uguaglianza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/is +--- +
{{JSRef}}
+ +

Il metodo Object.is() determina se i due parametri di input hanno lo stesso valore.

+ +

Sintassi

+ +
Object.is(value1, value2);
+ +

Parametri

+ +
+
value1
+
Il primo valore da comparare.
+
value2
+
Il secondo valore da comparare.
+
+ +

Return value

+ +

A {{jsxref("Boolean")}} indicating whether or not the two arguments are the same value.

+ +

Descrizione

+ +

Object.is() determina se due valori sono uguali. Due valori sono uguali se sono :

+ + + +

Questo non è la stessa uguaglianza dell'operatore {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}. L'operatore {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} applica varie conversioni ad entrambi (se non sono dello stesso tipo) prima di testare l'uguaglianza (ad esempio, "" == false risultando true), ma Object.is non converte i loro valori.

+ +

Inoltre questo non è la stessa uguaglianza dell'operatore {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}. L'operatore {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} (ed anche l'operatore {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}) trattano i numeri -0 e +0 come uguali e trattano {{jsxref("Number.NaN")}} differentemente da {{jsxref("NaN")}}.

+ +

Esempi

+ +
Object.is('foo', 'foo');     // true
+Object.is(window, window);   // true
+
+Object.is('foo', 'bar');     // false
+Object.is([], []);           // false
+
+var test = { a: 1 };
+Object.is(test, test);       // true
+
+Object.is(null, null);       // true
+
+// Casi speciali
+Object.is(0, -0);            // false
+Object.is(-0, -0);           // true
+Object.is(NaN, 0/0);         // true
+
+ +

Polyfill

+ +
if (!Object.is) {
+  Object.is = function(x, y) {
+    // Algoritmo SameValue
+    if (x === y) { // Steps 1-5, 7-10
+      // Steps 6.b-6.e: +0 != -0
+      return x !== 0 || 1 / x === 1 / y;
+    } else {
+     // Step 6.a: NaN == NaN
+     return x !== x && y !== y;
+    }
+  };
+}
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-object.is', 'Object.is')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-object.is', 'Object.is')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità coi browser

+ +
+ + +

{{Compat("javascript.builtins.Object.is")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/isfrozen/index.html b/files/it/web/javascript/reference/global_objects/object/isfrozen/index.html new file mode 100644 index 0000000000..b1220f1ae5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/isfrozen/index.html @@ -0,0 +1,184 @@ +--- +title: Object.isFrozen() +slug: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +tags: + - ECMAScript 5 + - Function + - Italian + - Italiano + - JavaScript + - JavaScript 1.8.5 + - Method + - Object + - Oggetto + - funzione + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +--- +
{{JSRef}}
+ +

Il metodo Object.isFrozen() determina se un oggetto è {{jsxref("Object.freeze()", "congelato", "", 1)}}.

+ +
{{EmbedInteractiveExample("pages/js/object-isfrozen.html")}}
+ + + +

Syntax

+ +
Object.isFrozen(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da controllare.
+
+ +

Valori di ritorno

+ +

Un {{jsxref("Boolean")}} che indica se l'oggetto è congelato oppure no.

+ +

Description

+ +

Un oggetto è congelato solo e soltanto se non è {{jsxref("Object.isExtensible()", "estensibile", "", 1)}}, tutte le sue proprietà sono non-configurabili, e tutte le sue proprietà "data" (che non sono proprietà "accessor", quindi non hanno componenti getter o setters) non sono sovrascrivibili.

+ +

Esempi

+ +
// Un nuovo oggetto è estensibile, quindi non è congelato.
+Object.isFrozen({}); // === false
+
+// Un oggetto vuoto che non è estensibile
+// è vacuamente congelato.
+var vacuouslyFrozen = Object.preventExtensions({});
+Object.isFrozen(vacuouslyFrozen); // === true
+
+// Un nuovo oggetto con una sola proprietà è estensibile,
+// quindi non è congelato.
+var oneProp = { p: 42 };
+Object.isFrozen(oneProp); // === false
+
+// Prevenire le estensioni dell'oggetto, comunque non
+// lo rende congelato, perché la proprietà è comunque
+// configurabile(e sovrascrivibile).
+Object.preventExtensions(oneProp);
+Object.isFrozen(oneProp); // === false
+
+// ...ma poi cancellare quella proprietà, rende l'oggetto
+// vacuamente congelato.
+delete oneProp.p;
+Object.isFrozen(oneProp); // === true
+
+// Un oggetto non-estensibile con una proprietà non-sovrascrivibile,
+// ma comunque configurabile, non è congelato.
+var nonWritable = { e: 'plep' };
+Object.preventExtensions(nonWritable);
+Object.defineProperty(nonWritable, 'e', {
+  writable: false
+}); // rende non-sovrascrivibile
+Object.isFrozen(nonWritable); // === false
+
+// Cambiare quella proprietà in non-configurabile
+// rende l'oggetto congelato.
+Object.defineProperty(nonWritable, 'e', {
+  configurable: false
+}); // rende non-configurabile
+Object.isFrozen(nonWritable); // === true
+
+// Un oggetto non-estensibile con una proprietà non-configurabile
+// ma comunque sovrascribile, non è congelato.
+var nonConfigurable = { release: 'the kraken!' };
+Object.preventExtensions(nonConfigurable);
+Object.defineProperty(nonConfigurable, 'release', {
+  configurable: false
+});
+Object.isFrozen(nonConfigurable); // === false
+
+// Cambiare quella proprietà in non-sovrascribile,
+// allora rende l'oggetto congelato.
+Object.defineProperty(nonConfigurable, 'release', {
+  writable: false
+});
+Object.isFrozen(nonConfigurable); // === true
+
+// Un oggetto non-estensibile con una configurabile
+// proprietà "accessor", non è congelato.
+var accessor = { get food() { return 'yum'; } };
+Object.preventExtensions(accessor);
+Object.isFrozen(accessor); // === false
+
+// ...ma poi rendere quella proprietà non-configurabile
+// congela l'oggetto.
+Object.defineProperty(accessor, 'food', {
+  configurable: false
+});
+Object.isFrozen(accessor); // === true
+
+// Ma il metodo più veloce per congelare un oggetto,
+// è utilizzare il metodo Object.freeze su di esso.
+var frozen = { 1: 81 };
+Object.isFrozen(frozen); // === false
+Object.freeze(frozen);
+Object.isFrozen(frozen); // === true
+
+// Per definizione, un oggetto congelato non è estensibile.
+Object.isExtensible(frozen); // === false
+
+// E sempre per definizione, un oggetto congelato è anche sigillato.
+Object.isSealed(frozen); // === true
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un'oggetto, allora verrà generato un {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già congelato, e perciò verrà semplicemente ritornato true.

+ +
Object.isFrozen(1);
+// TypeError: 1 non è un oggetto (codice in ES5)
+
+Object.isFrozen(1);
+// true                          (codice in ES2015)
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.12', 'Object.isFrozen')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.isfrozen', 'Object.isFrozen')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.isfrozen', 'Object.isFrozen')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Object.isFrozen")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/issealed/index.html b/files/it/web/javascript/reference/global_objects/object/issealed/index.html new file mode 100644 index 0000000000..d3bdf1b76b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/issealed/index.html @@ -0,0 +1,146 @@ +--- +title: Object.isSealed() +slug: Web/JavaScript/Reference/Global_Objects/Object/isSealed +tags: + - ECMAScript 5 + - Function + - Italian + - Italiano + - JavaScript + - JavaScript 1.8.5 + - Method + - Object + - Oggetto + - funzione + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed +--- +
{{JSRef}}
+ +

Il metodo Object.isSealed() determina se un oggetto è sigillato.

+ +
{{EmbedInteractiveExample("pages/js/object-issealed.html")}}
+ + + +

Syntax

+ +
Object.isSealed(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da controllare.
+
+ +

Valore di ritorno

+ +

Un {{jsxref("Boolean")}} che indica se l'oggetto è congelato oppure no.

+ +

Descrizione

+ +

Ritorna true se l'oggetto è sigillato, altrimenti false. Un oggetto  è sigillato se non è {{jsxref("Object.isExtensible", "estensibile", "", 1)}} e se tutte le sue proprietà sono non-configurabili e non possono essere rimosse (ma non necessariamente non-sovrascrivibili).

+ +

Esempi

+ +
// Gli oggetti non sono sigillati di default.
+var empty = {};
+Object.isSealed(empty); // === false
+
+// Se rendi un oggetto vuoto non-estensibile,
+// è vacuamente sigillato.
+Object.preventExtensions(empty);
+Object.isSealed(empty); // === true
+
+// Lo stesso non si verifica con un oggetto non vuoto,
+// a meno che le sue proprietà non sono tutte non-configurabili.
+var hasProp = { fee: 'fie foe fum' };
+Object.preventExtensions(hasProp);
+Object.isSealed(hasProp); // === false
+
+// Ma rendere tutte le sue proprietà non-configurabili
+// rende l'oggetto effettivamente sigillato.
+Object.defineProperty(hasProp, 'fee', {
+  configurable: false
+});
+Object.isSealed(hasProp); // === true
+
+// Il metodo più veloce per sigillare un oggetto, ovviamente,
+// è il metodo Object.seal.
+var sealed = {};
+Object.seal(sealed);
+Object.isSealed(sealed); // === true
+
+// Un oggetto sigillato è, per definizione, non-estensibile.
+Object.isExtensible(sealed); // === false
+
+// Un oggetto sigillato può anche essere congelato,
+// ma non è necessario.
+Object.isFrozen(sealed); // === true
+// (tutte le proprietà sono anche non-sovrascrivibili)
+
+var s2 = Object.seal({ p: 3 });
+Object.isFrozen(s2); // === false
+// ('p' è comunque sovrascrivibile)
+
+var s3 = Object.seal({ get p() { return 0; } });
+Object.isFrozen(s3); // === true
+// (per le proprietà "accessor", è importante solo la configurabilità della proprietà)
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un'oggetto, allora verrà generato un {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già sigillato, e perciò verrà semplicemente ritornato true.

+ +
Object.isSealed(1);
+// TypeError: 1 non è un oggetto (codice in ES5)
+
+Object.isSealed(1);
+// true                          (codice in ES2015)
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.11', 'Object.isSealed')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Object.isSealed")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/keys/index.html b/files/it/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..ed748c0fad --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,167 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Reference/Global_Objects/Object/keys +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 + - Metodi + - Oggetti +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +--- +
+ {{JSRef("Global_Objects", "Object")}}
+

Sommario

+

Il metodo Object.keys() restituisce un array contenente le proprietà enumerabili di un dato oggetto, nel medesimo ordine fornito da un ciclo for...in  (la differenza è che un ciclo for-in enumera anche le proprietà nella catena di prototipi).

+

Sintassi

+
Object.keys(obj)
+

Parametri

+
+
+ obj
+
+ L'oggetto del quale si devono restituire le proprietà enumerabili.
+
+

Descrizione

+

Object.keys restituisce un array i quali elementi sono stringhe corrispondenti alle proprietà enumerabili trovate direttamente in obj. L'ordine delle proprietà è lo stesso di quello dato ciclando manualmente sulle proprietà dell'oggetto.

+

Esempi

+
var arr = ["a", "b", "c"];
+alert(Object.keys(arr)); // chiama alert con argomento "0,1,2"
+
+// array like object
+var obj = { 0 : "a", 1 : "b", 2 : "c"};
+alert(Object.keys(obj)); // chiama alert con argomento "0,1,2"
+
+// array like object with random key ordering
+var an_obj = { 100: "a", 2: "b", 7: "c"};
+alert(Object.keys(an_obj)); // chiama alert con argomento "2, 7, 100"
+
+// getFoo is property which isn't enumerable
+var my_obj = Object.create({}, { getFoo : { value : function () { return this.foo } } });
+my_obj.foo = 1;
+
+alert(Object.keys(my_obj)); // chiama alert con foo come unico argomento
+
+

Per ottenere tutte le proprietà, anche quelle non enumerabili, si veda {{jsxref("Object.getOwnPropertyNames")}}.

+

Polyfill

+

Per aggiungere un supporto equivalente a Object.keys, in ambienti datati che non lo supportino nativamente, si copi il seguente frammento di codice:

+
// Da https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
+if (!Object.keys) {
+  Object.keys = (function () {
+    'use strict';
+    var hasOwnProperty = Object.prototype.hasOwnProperty,
+        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
+        dontEnums = [
+          'toString',
+          'toLocaleString',
+          'valueOf',
+          'hasOwnProperty',
+          'isPrototypeOf',
+          'propertyIsEnumerable',
+          'constructor'
+        ],
+        dontEnumsLength = dontEnums.length;
+
+    return function (obj) {
+      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
+        throw new TypeError('Object.keys called on non-object');
+      }
+
+      var result = [], prop, i;
+
+      for (prop in obj) {
+        if (hasOwnProperty.call(obj, prop)) {
+          result.push(prop);
+        }
+      }
+
+      if (hasDontEnumBug) {
+        for (i = 0; i < dontEnumsLength; i++) {
+          if (hasOwnProperty.call(obj, dontEnums[i])) {
+            result.push(dontEnums[i]);
+          }
+        }
+      }
+      return result;
+    };
+  }());
+}
+
+

Si noti che il codice sopra include chiavi non-enumerabili in IE7 (e forse IE8), nel caso in cui si passi un oggetto proveniente da un'altra finestra.

+

Per un semplice polyfill, si veda Javascript - Object.keys Browser Compatibility.

+

Specifiche

+ + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Definizione iniziale.
+ implementato in in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES6')}} 
+

Compatibilità dei browser

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Supporto base4 (2.0)59125
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Supporto base{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+

Basato su Kangax's compat table.

+

Vedere anche

+ diff --git a/files/it/web/javascript/reference/global_objects/object/observe/index.html b/files/it/web/javascript/reference/global_objects/object/observe/index.html new file mode 100644 index 0000000000..4307b4e75f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/observe/index.html @@ -0,0 +1,189 @@ +--- +title: Object.observe() +slug: Web/JavaScript/Reference/Global_Objects/Object/observe +translation_of: Archive/Web/JavaScript/Object.observe +--- +
{{JSRef}} {{obsolete_header}}
+ +

Sommario

+ +

Il metodo Object.observe() è usato per l'osservazione asincrona dei cambiamenti di un oggetto. Esso fornisce uno stream dei cambiamenti nell'ordine in cui si verificano.

+ +

Sintassi

+ +
Object.observe(obj, callback[, acceptList])
+ +

Parametri

+ +
+
obj
+
L'oggetto che verrà osservato.
+
callback
+
La funzione richiamata ogni volta che si verificano delle modifiche, con i seguenti argomenti: +
+
changes
+
Un array di oggetti di oggetti che rappresentano una modifica. Le properties di questi oggetti sono: +
    +
  • name: Il nome della property che è stata modificata.
  • +
  • object: L'oggetto modificato dopo che la modifica è avvenuta.
  • +
  • type: Una stringa che indica il tipo di modifica in atto. Può essere valorizzata con "add", "update" o "delete".
  • +
  • oldValue: Solo per i tipi "update" e "delete". Indica il valore prima della modifica.
  • +
+
+
+
+
acceptList
+
La lista dei tipi di modifiche che possono essere osservate su un dato oggetto per un dato callback. Se omesso, sarà usato l'array ["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"].
+
+ +

Descrizione

+ +

La funzione callback è chiamata ogni volta che una modifica viene fatta sull'obj. Ad essa viene passata un'array di tutte le modifiche, nell'ordine in cui si verificano.

+ +

Esempi

+ +

Esempio: Log di tutti e sei differenti tipi

+ +
var obj = {
+  foo: 0,
+  bar: 1
+};
+
+Object.observe(obj, function(changes) {
+  console.log(changes);
+});
+
+obj.baz = 2;
+// [{name: 'baz', object: <obj>, type: 'add'}]
+
+obj.foo = 'hello';
+// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}]
+
+delete obj.baz;
+// [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}]
+
+Object.defineProperty(obj, 'foo', {writable: false});
+// [{name: 'foo', object: <obj>, type: 'reconfigure'}]
+
+Object.setPrototypeOf(obj, {});
+// [{name: '__proto__', object: <obj>, type: 'setPrototype', oldValue: <prototype>}]
+
+Object.seal(obj);
+// [
+//   {name: 'foo', object: <obj>, type: 'reconfigure'},
+//   {name: 'bar', object: <obj>, type: 'reconfigure'},
+//   {object: <obj>, type: 'preventExtensions'}
+// ]
+
+ +

Esempio: Data Binding

+ +
// A user model
+var user = {
+  id: 0,
+  name: 'Brendan Eich',
+  title: 'Mr.'
+};
+
+// Create a greeting for the user
+function updateGreeting() {
+  user.greeting = 'Hello, ' + user.title + ' ' + user.name + '!';
+}
+updateGreeting();
+
+Object.observe(user, function(changes) {
+  changes.forEach(function(change) {
+    // Any time name or title change, update the greeting
+    if (change.name === 'name' || change.name === 'title') {
+      updateGreeting();
+    }
+  });
+});
+
+ +

Esempio: Tipo di modifica personalizzata

+ +
// A point on a 2D plane
+var point = {x: 0, y: 0, distance: 0};
+
+function setPosition(pt, x, y) {
+  // Performing a custom change
+  Object.getNotifier(pt).performChange('reposition', function() {
+    var oldDistance = pt.distance;
+    pt.x = x;
+    pt.y = y;
+    pt.distance = Math.sqrt(x * x + y * y);
+    return {oldDistance: oldDistance};
+  });
+}
+
+Object.observe(point, function(changes) {
+  console.log('Distance change: ' + (point.distance - changes[0].oldDistance));
+}, ['reposition']);
+
+setPosition(point, 3, 4);
+// Distance change: 5
+
+ +

Specifiche

+ +

Argomentazione proposta per ECMAScript 7.

+ +

Compatibilita browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatNo}}{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/prototype/index.html b/files/it/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..ea834e65de --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,214 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Sommario

+ +

La proprietà Object.prototype rappresenta l'oggetto prototipo di {{jsxref("Global_Objects/Object", "Object")}}.

+ +

{{js_property_attributes(0, 0, 0)}}

+ +

Descrizione

+ +

In JavaScript, tutti gli oggetti sono discendenti di {{jsxref("Global_Objects/Object", "Object")}}; tutti gli oggetti ereditano metodi e proprietà di Object.prototype (tranne nel caso l'oggetto abbia il prototipo uguale a {{jsxref("Global_Objects/null", "null")}}, quindi creati con il metodo {{jsxref("Object.create", "Object.create(null)")}}), anche se questi possono essere sovrascritti. Per esempio, i prototipi degli altri costruttori sovrascrivono la proprietà constructor e forniscono un loro metodo {{jsxref("Object.prototype.toString", "toString()")}}. I cambiamenti al prototipo di Object vengono estesi a tutti gli oggetti, eccetto quelli che sovrascrivono le proprietà e i metodi cambiati.

+ +

Proprietà

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
Specifica la funzione che ha creato l'oggetto a partire dal prototipo.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
È un riferimento all'oggetto usato come prototipo quando l'oggetto è stato istanziato.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
+
Permette di definire una funzione che venga chiamata quando viene chiamato un metodo non definito.
+
{{jsxref("Object.prototype.__count__")}} {{obsolete_inline}}
+
Rappresenta il numero di proprietà persenti in un oggetto, ma è stato rimosso.
+
{{jsxref("Object.prototype.__parent__")}} {{obsolete_inline}}
+
Rappresenta il contesto di un oggetto, ma è stato rimosso.
+
+ +

Metodi

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associa una funzione a una proprietà di un oggetto. Quando si tenta di leggere il valore di tale proprietà, viene eseguita la funzione e restituito il valore che restituisce.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associa una funzione a una proprietà di un oggetto. Quando si tenta di cambiare il valore di tale proprietà, viene eseguita la funzione.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Restituisce la funzione definita tramite {{jsxref("Object.prototype.defineGetter", "__defineGetter__()")}}.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Restituisce la funzione definita tramite {{jsxref("Object.prototype.defineSetter", "__defineSetter__()")}}.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
Determina se l'oggetto contiene direttamente una proprietà (non ereditata tramite il prototipo).
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
Determina se un oggetto fa parte della catena dei prototipi dell'oggetto sul quale è richiamato questo metodo.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
Determina se l'attributo DontEnum di ECMAScript interno è presente.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
Restituisce una stringa contenente il codice sorgente di un oggetto rappresentante l'oggetto sul quale questo metodo viene richiamato; puoi usare questo valore per creare un nuovo oggetto.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
Richiama {{jsxref("Object.prototype.toString", "toString()")}}.
+
{{jsxref("Object.prototype.toString()")}}
+
Restituisce la rappresentazione dell'oggetto sotto forma di stringa.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
Termina di osservare i cambiamenti di una proprietà dell'oggetto.
+
{{jsxref("Object.prototype.valueOf()")}}
+
Ritorna il valore primitivo dell'oggetto.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
Inizia a osservare i cambiamenti di una proprietà di un oggetto.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
Esegue una stringa di codice JavaScript nel contesto dell'oggetto, ma è stato rimosso.
+
+ +

Esempi

+ +

Siccome in JavaScript gli oggetti non sono sub-classabili in modo "standard", il prototipo è una soluzione utile per creare un oggetto che funzioni da "classe di base" che contenga dei metodi comuni a più oggetti. Per esempio:

+ +
var Persona = function() {
+  this.saParlare = true;
+};
+
+Persona.prototype.saluta = function() {
+  if (this.saParlare) {
+    console.log('Ciao, mi chiamo ' + this.nome);
+  }
+};
+
+var Dipendente = function(nome, titolo) {
+  Persona.call(this);
+  this.nome = nome;
+  this.titolo = titolo;
+};
+
+Dipendente.prototype = Object.create(Persona.prototype);
+Dipendente.prototype.constructor = Dipendente;
+
+Dipendente.prototype.saluta = function() {
+  if (this.saParlare) {
+    console.log('Ciao mi chiamo ' + this.nome + ' e lavoro come ' + this.titolo);
+  }
+};
+
+var Cliente = function(nome) {
+  Persona.call(this);
+  this.nome = nome;
+};
+
+Cliente.prototype = Object.create(Persona.prototype);
+Cliente.prototype.constructor = Cliente;
+
+var Mimo = function(nome) {
+  Persona.call(this);
+  this.nome = nome;
+  this.saParlare = false;
+};
+
+Mimo.prototype = Object.create(Persona.prototype);
+Mimo.prototype.constructor = Mimo;
+
+var bob = new Dipendente('Bob', 'Architetto');
+var joe = new Cliente('Joe');
+var rg = new Dipendente('Red Green', 'Tuttofare');
+var mike = new Cliente('Mike');
+var mime = new Mimo('Mimo');
+bob.saluta();
+joe.saluta();
+rg.saluta();
+mike.saluta();
+mime.saluta();
+
+ +

Stamperà:

+ +
Ciao, mi chiamo Bob e lavoro come Architetto
+Ciao, mi chiamo Joe
+Ciao, mi chiamo Red Green, e lavoro come Tuttofare
+Ciao, mi chiamo Mike
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition. Implemented in JavaScript 1.0.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/seal/index.html b/files/it/web/javascript/reference/global_objects/object/seal/index.html new file mode 100644 index 0000000000..4d301b568c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/seal/index.html @@ -0,0 +1,157 @@ +--- +title: Object.seal() +slug: Web/JavaScript/Reference/Global_Objects/Object/seal +tags: + - ECMAScript 5 + - Italian + - Italiano + - JavaScript + - JavaScript 1.8.5 + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/seal +--- +
{{JSRef}}
+ +

Il metodo Object.seal() "sigilla" un oggetto, e ciò rende impossibile l'aggiunta di nuove proprietà e rende tutte le proprietà esistenti non-configurabili. I valori delle proprietà presenti possono comunque essere cambiati, finché sono sovrascrivibili.

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-seal.html")}}
+ + + +

Sintassi

+ +
Object.seal(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da sigillare.
+
+ +

Valore di ritorno

+ +

L'oggetto sigillato.

+ +

Descrizione

+ +

Di default, gli oggetti sono {{jsxref("Object.isExtensible()", "estensibili", "", 1)}} (possono essergli aggiunte nuove proprietà). Sigillare un oggetto rende impossibile l'aggiunta di nuove proprietà e rende tutte le proprietà esistenti non-configurabili. Questo rende le proprietà dell'oggetto statiche ed immutabili. Rendere tutte le proprietà non-configurabili, inoltre, rende impossibile la conversione da proprietà "data" a proprietà "accessor" e viceversa, ma non rende impossibile la modifica dei valori delle proprietà "data". Qualsiasi tentativo di aggiungere o rimuovere proprietà ad un oggetto sigillato, o convertire una proprietà "data" in una proprietà "accessor" o viceversa, fallirebbe, o in modo silenzioso o  attraverso il ritorno di un {{jsxref("TypeError")}} (più frequentemente, ma non necessariamente, quest'ultimo scenario accadrebbe in {{jsxref("Strict_mode", "strict mode", "", 1)}}).

+ +

Le catene di prototipi non vengono sigillate. Invece, la proprietà {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} viene sigillata.

+ +

Ritorna l'oggetto passato ma sigillato.

+ +

Examples

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// Nuove proprietà potrebbero essere aggiunte, proprietà esistenti
+// potrebbero essere modificate o rimosse.
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+var o = Object.seal(obj);
+
+o === obj; // true
+Object.isSealed(obj); // === true
+
+// Cambiare proprietà su un oggetto sigillato
+// è ancora possibile.
+obj.foo = 'quux';
+
+// Ma non puoi convertire proprietà "data" in proprietà "accessor"
+// o viceversa.
+Object.defineProperty(obj, 'foo', {
+  get: function() { return 'g'; }
+}); // genera un TypeError
+
+// Ora, qualunque cambiamento, eccetto i valori delle proprietà,
+// fallirà.
+obj.quaxxor = 'the friendly duck';
+// silenziosamente non aggiunge la proprietà, per cui non genera errori od eccezioni
+delete obj.foo;
+// silenziosamente non rimuove la proprietà, per cui non genera errori od eccezioni
+
+// ...ed in strict mode, aggiungere o rimuovere proprietà
+// genererà TypeErrors.
+function fail() {
+  'use strict';
+  delete obj.foo; // genera un TypeError
+  obj.sparky = 'arf'; // genera un TypeError
+}
+fail();
+
+// Anche aggiungere proprietà tramite
+// Object.defineProperty genererà l'errore.
+Object.defineProperty(obj, 'ohai', {
+  value: 17
+}); // genera un TypeError
+Object.defineProperty(obj, 'foo', {
+  value: 'eit'
+}); // modifica il valore di una proprietà esistente
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un'oggetto, allora verrà generato un {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già sigillato, e verrà perciò semplicemente ritornato.

+ +
Object.seal(1);
+// TypeError: 1 non è un oggetto (codice in ES5)
+
+Object.seal(1);
+// 1                             (codice in ES2015)
+
+ +

Differenza con Object.freeze()

+ +

Le proprietà esistenti in oggetti congelati con Object.freeze() sono rese immutabili. Gli oggetti sigillati con Object.seal() possono ricevere modifiche alle proprietà esistenti.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.8', 'Object.seal')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.seal', 'Object.seal')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.seal', 'Object.seal')}}{{Spec2('ESDraft')}}
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Object.seal")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/tostring/index.html b/files/it/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..5a77ea1a3e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,170 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toString +tags: + - JavaScript + - Method + - Object + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Sommario

+ +

Il metodo toString() restituisce una stringa a che rappresenta l'oggetto.

+
{{EmbedInteractiveExample("pages/js/object-prototype-tostring.html")}}
+ + +

Sintassi

+ +
obj.toString()
+ +

Descrizione

+ +

Ogni oggetto ha un metodo toString() che è automaticamente chiamato quando l'oggetto deve essere rappresentato come valore testuale o quando l'oggetto è referenziato in un contesto in cui viene attesa una stringa. Di default, il metodo toString() è ereditato da ogni oggetto che discende da Object. Se il metodo non è sovrascritto in un oggetto personalizzato, toString() restituisce "[object type]", dove type è il tipo di oggetto. Il codice di seguito lo illustra:

+ +
var o = new Object();
+o.toString();           // returns [object Object]
+
+ +
+

Nota: A partire da JavaScript 1.8.5 toString() richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce [object Null], e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce [object Undefined], come definito nella versione 5 di ECMAScript e nei succcessivi Errata. Vedi {{anch("Example:_Using_toString_to_detect_object_type", "Using toString to detect object type")}}.

+
+ +

Esempi

+ +

Esempio: Sovrascrittura del metodo di default toString 

+ +

Puoi creare una funzione che deve essere richiamata al posto del default metodo toString(). Il metodo toString() non prende argomenti e deve restituire una stringa. Esso può assumere qualunque valore tu voglia, ma sarà molto utile se comunichi informazioni sull'oggetto.

+ +

Il codice seguente definisce l'oggetto Dog e crea theDog, ovvero un oggetto di tipo Dog:

+ +
function Dog(name, breed, color, sex) {
+  this.name = name;
+  this.breed = breed;
+  this.color = color;
+  this.sex = sex;
+}
+
+theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
+
+ +

Richiamando il metodo toString() su questo oggetto personalizzato, esso restituisce il valore di default ereditato da {{jsxref("Global_Objects/Object", "Object")}}:

+ +
theDog.toString(); // returns [object Object]
+
+ +

Il codice seguente crea e assegna il metodo dogToString() per sovrascrivere il metodo di default toString(). Questa funzione genera una stringa contenente i valori name, breed, color e sex dell'oggetto, nella forma di "property = value;".

+ +
Dog.prototype.toString = function dogToString() {
+  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
+  return ret;
+}
+
+ +

Col precedente codice, la funzione dogToString() è richiamata automaticamente da JavaScript ogni volta che l'oggetto theDog è usato in un contesto string, e restituisce la seguente stringa:

+ +
Dog Gabby is a female chocolate Lab
+
+ +

Esempio: Uso di toString() per individuare l'oggetto class

+ +

toString() può essere usato con ogni oggetto e permette di ottenere il suo class. Per usare Object.prototype.toString() con ogni oggetto, c'è bisogno di richiamare {{jsxref("Function.prototype.call()")}} o {{jsxref("Function.prototype.apply()")}} su di esso, passando l'oggetto che si cerca di ispezionare come primo parametro chiamato thisArg.

+ +
var toString = Object.prototype.toString;
+
+toString.call(new Date);    // [object Date]
+toString.call(new String);  // [object String]
+toString.call(Math);        // [object Math]
+
+// Since JavaScript 1.8.5
+toString.call(undefined);   // [object Undefined]
+toString.call(null);        // [object Null]
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommento
ECMAScript 1 Edizione.StandardDefinizione iniziale. Implementato in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}{{Spec2('ES5.1')}}Richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce [object Null], e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ES6')}}
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaratteristicheChromeFirefox (Gecko)Internet ExplorerOperaSafari
Support Base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Support Base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/parsefloat/index.html b/files/it/web/javascript/reference/global_objects/parsefloat/index.html new file mode 100644 index 0000000000..f587064676 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/parsefloat/index.html @@ -0,0 +1,139 @@ +--- +title: parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/parseFloat +translation_of: Web/JavaScript/Reference/Global_Objects/parseFloat +--- +
+
+
+ {{jsSidebar("Objects")}}
+
+
+

Sommario

+

La funzione parseFloat()  riceve una stringa come argomento e ritorna un numero in virgola mobile.

+

Sintassi

+
parseFloat(string)
+

Parametri

+
+
+ string
+
+ Una stringa che rapprestena il valore da analizzare.
+
+

Descrizione

+

parseFloat è una funzione primo livello ( globale ) e non è associata con nessun oggetto.

+

parseFloat analizza il parametro rappresentato da una stringa e ritorna un numero in virgola mobile. Se rileva un carattere diverso da segni ( + o - ), numeri ( 0 - 9 ), punto di separazione decimale o un esponente, la funzione ritorna il valore fino a quel punto ignorando il carattere rilevato e tutti quelli successvi. Gli spazi bianchi, iniziali e finali, sono consentiti.

+

Se il primo carattere dell'argomento non può essere analizzato, parseFloat ritorna NaN.

+

Per questioni aritmetiche, il valore NaN non è di tipo numerico. Per determinare se il risultato di ParseFloat è  NaN occorre chiamare la funzione {{jsxref("Global_Objects/isNaN", "isNaN")}}. Se NaN viene utilizzato per un operazione aritmetica, la stessa risulterà NaN.

+

parseFloat può analizzare e ritornare il valore Infinity. La funzione {{jsxref("Global_Objects/isNaN", "isNaN")}} consente di determinare se il risultato è un numero finito  (not Infinity-Infinity, o NaN).

+

Esempi

+

Esempio: parseFloat ritorna un numero

+

Tutti gli esempi seguenti ritornano 3.14

+
parseFloat("3.14");
+parseFloat("314e-2");
+parseFloat("0.0314E+2");
+parseFloat("3.14altri caratteri non numerici");
+
+

Esempio: parseFloat ritorna NaN

+

L'esempio seguente ritorna il valore NaN

+
parseFloat("FF2");
+
+

Una funzione di analisi più approfondita.

+

Talvolta può essere necessario un maggior controllo sulla funzione di parse, le regular expression possono aiutare :

+
var filterFloat = function (value) {
+    if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
+      .test(value))
+      return Number(value);
+  return NaN;
+}
+
+console.log(filterFloat('421'));               // 421
+console.log(filterFloat('-421'));              // -421
+console.log(filterFloat('+421'));              // 421
+console.log(filterFloat('Infinity'));          // Infinito
+console.log(filterFloat('1.61803398875'));     // 1.61803398875
+console.log(filterFloat('421e+0'));            // NaN
+console.log(filterFloat('421hop'));            // NaN
+console.log(filterFloat('hop1.61803398875'));  // NaN
+
+

Nota: questo codice è a scopo esplicativo. La funzione non accetta numeri validi come 1. o .5+

+

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
ECMAScript 1a Edizione.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.3', 'parseFloat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-parsefloat-string', 'parseFloat')}}{{Spec2('ES6')}} 
+

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() }}
+
+

Leggi anche:

+ diff --git a/files/it/web/javascript/reference/global_objects/parseint/index.html b/files/it/web/javascript/reference/global_objects/parseint/index.html new file mode 100644 index 0000000000..c6300b4b3e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/parseint/index.html @@ -0,0 +1,190 @@ +--- +title: parseInt() +slug: Web/JavaScript/Reference/Global_Objects/parseInt +translation_of: Web/JavaScript/Reference/Global_Objects/parseInt +--- +
{{jsSidebar("Objects")}}
+ +

La funzione parseInt() analizza un argomento stringa e restituisce un numero intero della radice specificata (la base nei sistemi numerici matematici).

+ +
{{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}}
+ + + +

Sintassi

+ +
parseInt(string, radix);
+ +

Parametri

+ +
+
string
+
Il valore da analizzare. Se l'argomento string non è una stringa, viene convertito in una stringa (utilizzando l'operazione astratta ToString). Gli spazi bianchi iniziali nell'argomento stringa vengono ignorati.
+
radix
+
Un numero intero compreso tra 2 e 36 che rappresenta la radice (la base nei sistemi numerici matematici) della stringa sopra menzionata.
+
+ +

Valore di ritorno

+ +

Un numero intero analizzato dalla stringa specificata. Se il primo carattere non può essere convertito in un numero, viene restituito {{jsxref("NaN")}}.

+ +

Descrizione

+ +

La funzione parseInt converte il suo primo argomento in una stringa, lo analizza e restituisce un numero intero o NaN. Se non è NaN, il valore restituito sarà l'intero che è il primo argomento preso come numero nella radice specificata (base). Ad esempio, una radice di 10 indica la conversione da un numero decimale, 8 ottali, 16 esadecimali e così via. Per le radici sopra 10, le lettere dell'alfabeto indicano numeri maggiori di 9. Ad esempio, per i numeri esadecimali (base 16), vengono utilizzate le lettere da A a F.

+ +

Se parseInt incontra un carattere che non è un numero nella radice specificata, lo ignora e tutti i caratteri successivi e restituisce il valore intero analizzato fino a quel punto. parseInt tronca i numeri ai valori interi. Sono ammessi spazi iniziali e finali.

+ +

Poiché alcuni numeri includono il carattere e nella loro rappresentazione di stringa (ad esempio 6.022e23), l'uso di parseInt per troncare valori numerici produrrà risultati imprevisti se utilizzato su numeri molto grandi o molto piccoli. parseInt non dovrebbe essere usato come sostituto di {{jsxref("Math.floor()")}}.

+ +

Se radix è undefined o 0 (o assente), JavaScript assume quanto segue:

+ + + +

Se il primo carattere non può essere convertito in un numero, parseInt restituisce NaN.

+ +

Per scopi aritmetici, il valore NaN vnon è un numero in nessuna radice. È possibile chiamare la funzione {{jsxref("isNaN")}} per determinare se il risultato di parseInt è NaN. Se NaN viene passato alle operazioni aritmetiche, i risultati dell'operazione saranno anche NaN.

+ +

Per convertire il numero nella sua stringa letterale in una particolare radix, usa intValue.toString(radix).

+ +

Esempi

+ +

Usare parseInt

+ +

Tutti gli esempi seguenti restituiscono 15:

+ +
parseInt('0xF', 16);
+parseInt('F', 16);
+parseInt('17', 8);
+parseInt(021, 8);
+parseInt('015', 10);   // parseInt(015, 10); ritornerà 15
+parseInt(15.99, 10);
+parseInt('15,123', 10);
+parseInt('FXX123', 16);
+parseInt('1111', 2);
+parseInt('15 * 3', 10);
+parseInt('15e2', 10);
+parseInt('15px', 10);
+parseInt('12', 13);
+
+ +

I seguenti esempi restituiscono tutti NaN:

+ +
parseInt('Hello', 8); // Non è un numero
+parseInt('546', 2);   // Le cifre non sono valide per le rappresentazioni binarie
+
+ +

Tutti gli esempi seguenti restituiscono -15:

+ +
parseInt('-F', 16);
+parseInt('-0F', 16);
+parseInt('-0XF', 16);
+parseInt(-15.1, 10);
+parseInt('-17', 8);
+parseInt('-15', 10);
+parseInt('-1111', 2);
+parseInt('-15e1', 10);
+parseInt('-12', 13);
+
+ +

Tutti gli esempi seguenti restituiscono 4:

+ +
parseInt(4.7, 10);
+parseInt(4.7 * 1e22, 10); // Il numero molto grande diventa 4
+parseInt(0.00000000000434, 10); // Il numero molto piccolo diventa 4
+
+ +

L'esempio seguente restituisce 224:

+ +
parseInt('0e0', 16);
+
+ +

Interpretazioni ottali senza radix

+ +

Sebbene scoraggiato da ECMAScript 3 e proibito da ECMAScript 5, molte implementazioni interpretano una stringa numerica che inizia con uno 0 iniziale come ottale. Il seguente potrebbe avere un risultato ottale o potrebbe avere un risultato decimale. Specifica sempre una radice per evitare questo comportamento inaffidabile.

+ +
parseInt('0e0'); // 0
+parseInt('08'); // 0, '8' non è una cifra ottale.
+
+ +

ECMAScript 5 rimuove l'interpretazione ottale

+ +

La specifica ECMAScript 5 della funzione parseInt non consente più alle implementazioni di trattare le stringhe che iniziano con un carattere 0 come valori ottali. ECMAScript 5 afferma:

+ +

La funzione parseInt produce un valore intero dettato dall'interpretazione del contenuto dell'argomento stringa in base alla radice specificata. Lo spazio bianco principale nella stringa viene ignorato. Se radix non è definito o 0, si presume che sia 10 tranne quando il numero inizia con le coppie di caratteri 0x0X, nel qual caso si assume una radice di 16.

+ +

Ciò differisce da ECMAScript 3, che scoraggiava, ma consentiva l'interpretazione ottale.

+ +

Molte implementazioni non hanno adottato questo comportamento a partire dal 2013 e, poiché i browser più vecchi devono essere supportati, specificare sempre una radice.

+ +

Una funzione di analisi più rigorosa

+ +

A volte è utile avere un modo più rigoroso di analizzare i valori int. Le espressioni regolari possono aiutare:

+ +
var filterInt = function(value) {
+  if (/^(-|\+)?(\d+|Infinity)$/.test(value))
+    return Number(value);
+  return NaN;
+}
+
+console.log(filterInt('421'));               // 421
+console.log(filterInt('-421'));              // -421
+console.log(filterInt('+421'));              // 421
+console.log(filterInt('Infinity'));          // Infinity
+console.log(filterInt('421e+0'));            // NaN
+console.log(filterInt('421hop'));            // NaN
+console.log(filterInt('hop1.61803398875'));  // NaN
+console.log(filterInt('1.61803398875'));     // NaN
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.2', 'parseInt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-parseint-string-radix', 'parseInt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-parseint-string-radix', 'parseInt')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.parseInt")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/promise/all/index.html b/files/it/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..4d1c9a970c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,110 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +
{{JSRef}}
+ +

Il metodo Promise.all(iterable) restituisce una singola promise che viene risolta quando tutte le promise nell'iterable passate come parametro vengono risolte. Scatena una reject contenente la ragione della prima promise che viene respinta.

+ +

Sintassi

+ +
Promise.all(iterable);
+ +

Parameteri

+ +
+
iterable
+
Un oggetto iterabile, come un {{jsxref("Array")}}. See iterable.
+
+ +

Valore di ritorno

+ +

Un {{jsxref("Promise")}} che viene risolto quando tutti i promise nell'iterable passato come parametro vengono risolti, o scatena una reject contenente la ragione del primo promise che viene rigettato

+ +

Descrizione

+ +

Il metodo Promise.all ritorna un array di valori ritornati dai promise nell oggetto iterable che ha ricevuto. L'array dei valori ritornati mantiene lo stesso ordine dell'oggetto iterable originario e non l'ordine di risoluzione dei promise. Se uno dei valori dell'oggetto iterabile passato come parametro non un promise viene automaticamente convertito con {{jsxref("Promise.resolve")}}. 

+ +

Se uno qualsiasi dei promise passati viene rigettato, il metodo all Promise viene rigettato automaticamente con il valore del promise rigettato, scartando tutti i promise indipendentemente dal fatto che gli altri siano stati risolti o meno. Se viene passato un un array vuoto, allora questo metodo ritorna immediatamente.

+ +

Esempi

+ +

Usare Promise.all

+ +

Il metodo Promise.all aspetta la risoluzione di tutti i promise  (od il primo che viene rigettato).

+ +
var p1 = Promise.resolve(3);
+var p2 = 1337;
+var p3 = new Promise((resolve, reject) => {
+  setTimeout(resolve, 100, "foo");
+});
+
+Promise.all([p1, p2, p3]).then(values => {
+  console.log(values); // [3, 1337, "foo"]
+});
+ +

Promise.all comportamento fail-fast

+ +

Il metodo Promise.all viene rigettato se uno degli elementi viene rigettato e Promise.all viene rigettato immediatamente. In caso quattro promise vengono risolti dopo un  timeout, e uno viene rigettato immediatamente: allora Promise.all viene rigettato immediamente.

+ +
var p1 = new Promise((resolve, reject) => {
+  setTimeout(resolve, 1000, "one");
+});
+var p2 = new Promise((resolve, reject) => {
+  setTimeout(resolve, 2000, "two");
+});
+var p3 = new Promise((resolve, reject) => {
+  setTimeout(resolve, 3000, "three");
+});
+var p4 = new Promise((resolve, reject) => {
+  setTimeout(resolve, 4000, "four");
+});
+var p5 = new Promise((resolve, reject) => {
+  reject("reject");
+});
+
+Promise.all([p1, p2, p3, p4, p5]).then(value => {
+  console.log(value);
+}, reason => {
+  console.log(reason)
+});
+
+//From console:
+//"reject"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatusCommenti
{{SpecName('ES6', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES6')}}Definizione iniziale nello standard ECMA.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
+ +

Compatibilitá dei browser

+ + + +

{{Compat}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/promise/catch/index.html b/files/it/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..0b9b906153 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,124 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +
{{JSRef}}
+ +

Il metodo catch() restituisce una Promise e si occusa esclusivamente nei casi respinti. Si comporta come una chiamata {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.

+ +

 

+ +

Sintassi

+ +
p.catch(onRejected);
+
+p.catch(function(reason) {
+   // rejection
+});
+
+ +

Parametri

+ +
+
onRejected
+
Una {{jsxref("Function")}} chiamata quando la Promise viene respinta. Questa funzione richiede un parametro, la motivazione della respinta.
+
+ +

Descrizione

+ +

Il metodo catch può essere utile per gestire errori nella composizione delle promise.

+ +

Esempi

+ +

Uso del metodo catch

+ +
var p1 = new Promise(function(resolve, reject) {
+  resolve("Success");
+});
+
+p1.then(function(value) {
+  console.log(value); // "Success!"
+  throw "oh, no!";
+}).catch(function(e) {
+  console.log(e); // "oh, no!"
+});
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support32{{CompatGeckoDesktop(29.0)}} [1]{{CompatNo}}197.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(29.0)}} [1]{{CompatNo}}{{CompatNo}}832
+
+ +

[1] Gecko 24 has an experimental implementation of Promise, under the initial name of Future. It got renamed to its final name in Gecko 25, but disabled by default behind the flag dom.promise.enabled. Bug 918806 enabled Promises by default in Gecko 29.

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/promise/index.html b/files/it/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..d2f579bc51 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,248 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - ECMAScript 2015 + - JavaScript + - Promise + - async +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

Gli oggetti Promise sono usati per computazioni in differita e asincrone. Una Promise rappresenta un'operazione che non è ancora completata, ma lo sarà in futuro.

+ +

Sintassi

+ +
new Promise(function(resolve, reject) { ... });
+ +

Parametri

+ +
+
executor
+
+

Una funzione che ha due argomenti: resolve e reject.  Tale funzione viene chiamata immediatamente dall'implementazione della Promise, passando i due argomenti resolve e reject, che sono due funzioni. Le due funzioni resolve e reject, quando chiamate, risolvono o rigettano la promise. L'esecutore inizia del lavoro (solitamente asincrono), e, una volta completato, chiama resolve per risolvere la promise, o reject se c'è stato qualche errore. Se un errore viene sollevato nella funzione di esecuzione (executor) la promise viene rigettata.

+
+
+ +

Descrizione

+ +

Una Promise rappresenta un proxy per un valore non necessariamente noto quando la promise è stata creata.  Consente di associare degli handlers con il successo o il fallimento di un'azione asincrona  (e il "valore" in caso di successo, o la motivazione in caso di fallimento). Questo in pratica consente di utilizzare dei metodi asincroni di fatto come se fossero sincroni: la funzione che compie del lavoro asincrono non ritorna il valore di completamento ma ritorna una promise, tramite la quale si potrà ottenere il valore di completamento una volta che la promise sarà terminata.

+ +

Una Promise può presentarsi in uno dei seguenti stati:

+ + + +

Una promise in pending può evolvere sia in fulfilled con un valore, sia in rejected con una motivazione (errore). Quando accade una di queste situazioni, vengono chiamati gli handler associati che sono stati accodati dal metodo then della promise. (Se la promise è già stata soddisfatta o respinta quando viene agganciato l'handler, quest'ultimo verrà chiamato immediatamente, quindi non è necessario che gli handler vengano agganciati prima del completamento dell'operazione asincrona).

+ +

Poichè i metodi {{jsxref("Promise.then", "Promise.prototype.then")}} e {{jsxref("Promise.catch", "Promise.prototype.catch")}} restituiscono delle promise, è possibile concatenarli tramite l'operazione di composition.

+ +

+ +
+

Da non confondere con: molti altri linguaggi hanno meccanismi simili per la lazy evaluation ed il calcolo differito, che a loro volta vengono chiamati "promise" (es. Schemes). Le Promise in Javascript rappresentano un processo che è gia accaduto, che può essere concatenato con delle funzioni di callback. Se stai cercando di eseguire una lazy evaluation (valutazione non immediata) di un'espressione, considera l'utilizzo delle arrow function senza argomenti: f = () => expression per creare un'espressione non valutata immediatamente (lazy-evaluated) ed usare f() per valutarla.

+
+ +
+

Nota: Si dice che una promise è "ferma" (settled) se è soddisfatta o respinta, ma non in pending. Si può parlare anche di promessa "risolta" (resolved) quando la promise è ferma o è bloccata in una catena di promise. States and fates di Domenic Denicola contiene maggiori dettagli sulla terminologia riguardo le promise.

+
+ +

Proprietà

+ +
+
Promise.length
+
La proprietà length (lunghezza) ha come valore 1 (numero di argomenti del costruttore).
+
{{jsxref("Promise.prototype")}}
+
Rappresenta il prototype per il costruttore della Promise.
+
+ +

Metodi

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
Ritorna una promise che si risolve quando tutte le promises dell'argomento iterabile sono state risolte. Oppure, viene rigettato appena una promise dell'argomento di tipo Iterable viene rigettato. Se tutto va a buon fine, la promise viene completata con un array contenente i valori di completamento di ciascuna promise dell'iterable, nello stesso ordine di quello dell'iterable. In caso fallisca (cioè appena una prima promise dell'iterable fallisce), Promise.all viene rigettato con la ragione (errore) della prima promise che ha fallito. Questo è utile per aggregare insieme il risultato di più promises.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
Restituisce una promise che si risolve o respinge, non appena una delle promises dell'iterable si risolve o respinge, con il valore o la motivazione da quella promise.
+
+ +
+
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
+
Restituisce un oggetto Promise che è respinta con la data motivazione.
+
+ +
+
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
+
Restituise un oggetto Promise che è risolto con il valore dato. Se il valore é un thenable (es. ha un metodo then), la promise restituita "seguirà" quel thenable, usando il suo stato; altirmenti la promise restituita sarà soddisfatta con il valore. Generalmente, se non sei sicuro che un valore sia di tipo Promise usa {{jsxref("Promise.resolve", "Promise.resolve(value)")}} e lavora con il valore restituito dalla promise.
+
+ +

Promise prototype

+ +

Proprietà

+ +

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

+ +

Metodi

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

+ +

Creazione di una Promise

+ +

Un oggetto di tipo Promise, viene creato con la keyowrd new ed il suo costruttore. Questo costruttore accetta come argomento una funzione, chiamata "funzione esecutore (executor function)". Questa funzione accetta altre due funzioni come parametri. La prima (resolve) viene eseguita in modo asincrono quando l'operazione viene eseguita con successo e restituisce il risultato dell'operazione come valore. La seconda (reject) viene eseguita nel caso in cui l'operazione fallisca e restituisce il motivo per cui l'operazione non è stata eseguita: generalmente un oggetto di tipo Error

+ +
const myFirstPromise = new Promise((resolve, reject) => {
+  // esegue qualcosa di asincrono che eventualmente chiama:
+  //
+     resolve(someValue); // fulfilled
+  // oppure
+     reject("motivo del fallimento"); // rejected
+});
+ +

Per creare una funzione con il comportamento di Promise, semplicemente restituisci una promise

+ +
function myAsyncFunction(url) {
+  return new Promise((resolve, reject) => {
+    const xhr = new XMLHttpRequest();
+    xhr.open("GET", url);
+    xhr.onload = () => resolve(xhr.responseText);
+    xhr.onerror = () => reject(xhr.statusText);
+    xhr.send();
+  });
+}
+ +

Esempi

+ +

Esempio semplice

+ +
let myFirstPromise = new Promise((resolve, reject) => {
+  // Chiamiamo resolve(...) quando viene eseguito correttamente, e reject(...) quando fallisce.
+  // In questo esempio viene utilizzato setTimeout(...) per simulare un'operazione asincrona.
+  // Nella realtà probabilmente utilizzerai qualcosa del tipo XHR o HTML5 API.
+  setTimeout(function(){
+    resolve("Success!"); // È andato tutto perfettamente!
+  }, 250);
+});
+
+myFirstPromise.then((successMessage) => {
+  // successMessage viene passato alla funzione resolve(...) .
+  // Non deve essere necessariamente una stringa, ma nel caso sia solo un messaggio probabilmemte lo sarà.
+  console.log("Yay! " + successMessage);
+});
+ +

Esempio avanzato

+ +
<button id="btn">Make a promise!</button>
+<div id="log"></div>
+ +

Questo piccolo esempio mostra il meccanismo delle Promise. Il metodo testPromise() viene richiamato ogni volta che il {{HTMLElement("button")}} viene cliccato. Crea una promise che viene risolta correttamente (fulfilled), utilizzando {{domxref("window.setTimeout()")}} che incrementa il contatore ogni 1-3 secondi (random). Il costruttore Promise viene utilizzato per creare la promise.

+ +

La risoluzione della promise viene semplicemente loggata tramite una funzione di callback fulfill {{jsxref("Promise.prototype.then()","p1.then()")}}. Una serie di log mostrano che il comportamento sincrono del metodo è disaccoppiato rispetto all'esecuzione asincrona della promise.

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    let thisPromiseCount = ++promiseCount;
+
+    let log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Started (<small>Sync code started</small>)<br/>');
+
+    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
+    let p1 = new Promise(
+        // The resolver function is called with the ability to resolve or
+        // reject the promise
+       (resolve, reject) => {
+            log.insertAdjacentHTML('beforeend', thisPromiseCount +
+                ') Promise started (<small>Async code started</small>)<br/>');
+            // This is only an example to create asynchronism
+            window.setTimeout(
+                function() {
+                    // We fulfill the promise !
+                    resolve(thisPromiseCount);
+                }, Math.random() * 2000 + 1000);
+        }
+    );
+
+    // We define what to do when the promise is resolved with the then() call,
+    // and what to do when the promise is rejected with the catch() call
+    p1.then(
+        // Log the fulfillment value
+        function(val) {
+            log.insertAdjacentHTML('beforeend', val +
+                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
+        }).catch(
+        // Log the rejection reason
+       (reason) => {
+            console.log('Handle rejected promise ('+reason+') here.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Promise made (<small>Sync code terminated</small>)<br/>');
+}
+
+
+
+if ("Promise" in window) {
+  let btn = document.getElementById("btn");
+  btn.addEventListener("click",testPromise);
+} else {
+  log = document.getElementById('log');
+  log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface.";
+}
+ +

In questo esempio si comincia cliccando il bottone. Per testare necessiti di un browser che supporta le Promise. Cliccando il bottone diverse volte in un lasso di tempo breve vedrai che le funzioni verranno risolte una dopo l'altra.

+ +

Caricare un'immagine con XHR

+ +

Un'altro semplice esempio che utilizza le Promise e XMLHttpRequest mostra come caricare un'immagine è disponibile sul repository di MDN su Github. Puoi inoltre vederla in azione. Ogni azione è commentata e puoi seguire passo-passo come viene creata la Promise e gestita tramite XHR.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}{{Spec2('ES2015')}} +

Prima definizione in uno standard ECMA.

+
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} +

 

+
+ +

Supporto dei browser

+ +

{{Compat("javascript.builtins.Promise")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html b/files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html new file mode 100644 index 0000000000..f803b41255 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html @@ -0,0 +1,119 @@ +--- +title: handler.apply() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply +tags: + - ECMAScript 2015 + - JavaScript + - Proxy + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply +--- +
{{JSRef}}
+ +

Il metodo handler.apply() costituisce una trap per una chiamata a funzione.

+ +
{{EmbedInteractiveExample("pages/js/proxyhandler-apply.html", "taller")}}
+ + + +

Sintassi

+ +
var p = new Proxy(target, {
+  apply: function(target, thisArg, argumentsList) {
+  }
+});
+
+ +

Parametri

+ +

I seguenti parametri vengono passati al metodo apply. this è legato all'handler.

+ +
+
target
+
L'oggetto target.
+
thisArg
+
Il valore di this relativo alla chiamata.
+
argumentsList
+
La lista degli argomenti della chiamata.
+
+ +

Valore di ritorno

+ +

Il metodo apply può restituire qualsiasi valore.

+ +

Descrizione

+ +

Il metodo handler.apply è una trap per le chiamate a funzione.

+ +

Operazioni intercettate

+ +

Questa trap può intercettare le seguenti operazioni:

+ + + +

Invarianti

+ +

Se le seguenti invarianti non sono rispettate il proxy emetterà un TypeError:

+ + + +

Esempi

+ +

Il codice seguente intercetta una chiamata a funzione.

+ +
var p = new Proxy(function() {}, {
+  apply: function(target, thisArg, argumentsList) {
+    console.log('chiamato con: ' + argumentsList.join(', '));
+    return argumentsList[0] + argumentsList[1] + argumentsList[2];
+  }
+});
+
+console.log(p(1, 2, 3)); // "chiamato con: 1, 2, 3"
+                         // 6
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
+ + +

{{Compat("javascript.builtins.Proxy.handler.apply")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/proxy/handler/index.html b/files/it/web/javascript/reference/global_objects/proxy/handler/index.html new file mode 100644 index 0000000000..042e9b50b1 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/handler/index.html @@ -0,0 +1,83 @@ +--- +title: Proxy handler +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler +tags: + - ECMAScript 2015 + - JavaScript + - NeedsTranslation + - Proxy + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy +--- +
{{JSRef}}
+ +

The proxy's handler object is a placeholder object which contains traps for {{jsxref("Proxy", "proxies", "", 1)}}.

+ +

Methods

+ +

All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.

+ +
+
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}
+
A trap for {{jsxref("Object.getPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}
+
A trap for {{jsxref("Object.setPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}
+
A trap for {{jsxref("Object.isExtensible")}}.
+
{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}
+
A trap for {{jsxref("Object.preventExtensions")}}.
+
{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}
+
A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}.
+
{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}
+
A trap for {{jsxref("Object.defineProperty")}}.
+
{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}
+
A trap for the {{jsxref("Operators/in", "in")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}
+
A trap for getting property values.
+
{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}
+
A trap for setting property values.
+
{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}
+
A trap for the {{jsxref("Operators/delete", "delete")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}
+
A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}.
+
{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}
+
A trap for a function call.
+
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}
+
A trap for the {{jsxref("Operators/new", "new")}} operator.
+
+ +

Some non-standard traps are obsolete and have been removed.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ESDraft')}}The enumerate handler has been removed.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Proxy.handler")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/proxy/index.html b/files/it/web/javascript/reference/global_objects/proxy/index.html new file mode 100644 index 0000000000..fa35ff1d43 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/index.html @@ -0,0 +1,396 @@ +--- +title: Proxy +slug: Web/JavaScript/Reference/Global_Objects/Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy +--- +
+
{{JSRef}}
+ +
L'oggetto Proxy è utilizzato per definire comportamenti personalizzati per operazioni fondamentali (per esempio: ricerca delle proprietà, assegnazione, enumerazione, invocazione delle funzioni, ecc.).
+
+ +

Terminologia

+ +
+
handler
+
Oggetto placeholder, il quale contiene le trappole.
+
traps
+
I metodi che forniscono l'accesso alle proprietà. Questo è analogo al concetto di trappola nei sistemi operativi.
+
target
+
Oggetti, che i proxy virtualizzano (sostituiscono). Viene spesso utilizzato come back-end di archiviazione per il proxy. Le invarianti, riguardanti oggetti non estensibili o proprietà non configurabili, sono verificate prima di interagire con l'obiettivo.
+
+ +

Sintassi

+ +
var p = new Proxy(target, handler);
+
+ +

Parametri

+ +
+
target
+
Un oggetto target che il Proxy ingloberà. Può essere un qualsiasi tipo di oggetto, array nativi inclusi, funzioni o anche altri Proxy.
+
handler
+
Un oggetto le cui proprietà sono funzioni che definiscono i comportamenti del proxy quando un'operazione viene effettuata su di esso.
+
+ +

Metodi

+ +
+
{{jsxref("Proxy.revocable()")}}
+
Crea un oggetto Proxy revocabile.
+
+ +

Metodi dell'handler object

+ +

L'oggetto handler è un oggetto placeholder, il quale contiene le trappole per il Proxy.

+ +

Esempi

+ +

Esempio base

+ +

In questo esempio base il numero 37 viene restituito come valore di default quando l'oggetto non contiene la proprietà richiesta. Viene utilizzato il get handler.

+ +
var handler = {
+    get: function(target, name) {
+        return name in target ?
+            target[name] :
+            37;
+    }
+};
+
+var p = new Proxy({}, handler);
+p.a = 1;
+p.b = undefined;
+
+console.log(p.a, p.b); // 1, undefined
+console.log('c' in p, p.c); // false, 37
+
+ +

No-op forwarding proxy

+ +

In questo esempio viene utilizzato un semplice oggetto Javascript come target, al quale il proxy inoltrerà tutte le operazioni che sono state applicate su di esso. 

+ +
var target = {};
+var p = new Proxy(target, {});
+
+p.a = 37; // operazione inoltrata al target
+
+console.log(target.a); // 37. Operazione inoltrata con successo
+
+ +

Validation

+ +

Con un proxy, puoi facilmente validare il valore passato per un oggetto. In questo esempio viene utilizzato il  set handler.

+ +
let validator = {
+  set: function(obj, prop, value) {
+    if (prop === 'age') {
+      if (!Number.isInteger(value)) {
+        throw new TypeError('L\'età non è un numero intero');
+      }
+      if (value > 200) {
+        throw new RangeError('L\'età sembra non essere valida');
+      }
+    }
+
+    // Il comportamento di default da adoperare per memorizzare il valore
+    obj[prop] = value;
+
+    return true;
+  }
+};
+
+let person = new Proxy({}, validator);
+
+person.age = 100;
+console.log(person.age); // 100
+person.age = 'young'; // Lancia una eccezione
+person.age = 300; // Lancia una eccezione
+ +

Extending constructor

+ +

Una funzione proxy può facilmente estendere un costruttore con un nuovo costruttore. Questo esempio usa gli handler: construct e apply .

+ +
function extend(sup, base) {
+  var descriptor = Object.getOwnPropertyDescriptor(
+    base.prototype, 'constructor'
+  );
+  base.prototype = Object.create(sup.prototype);
+  var handler = {
+    construct: function(target, args) {
+      var obj = Object.create(base.prototype);
+      this.apply(target, obj, args);
+      return obj;
+    },
+    apply: function(target, that, args) {
+      sup.apply(that, args);
+      base.apply(that, args);
+    }
+  };
+  var proxy = new Proxy(base, handler);
+  descriptor.value = proxy;
+  Object.defineProperty(base.prototype, 'constructor', descriptor);
+  return proxy;
+}
+
+var Person = function(name) {
+  this.name = name;
+};
+
+var Boy = extend(Person, function(name, age) {
+  this.age = age;
+});
+
+Boy.prototype.sex = 'M';
+
+var Peter = new Boy('Peter', 13);
+console.log(Peter.sex);  // "M"
+console.log(Peter.name); // "Peter"
+console.log(Peter.age);  // 13
+ +

Manipulating DOM nodes

+ +

Alcune volte vorresti attivare o disattivare un attributo o una classe di due elementi differenti. Qui è mostrato come è possibile farlo utilizzando il set handler.

+ +
let view = new Proxy({
+  selected: null
+},
+{
+  set: function(obj, prop, newval) {
+    let oldval = obj[prop];
+
+    if (prop === 'selected') {
+      if (oldval) {
+        oldval.setAttribute('aria-selected', 'false');
+      }
+      if (newval) {
+        newval.setAttribute('aria-selected', 'true');
+      }
+    }
+
+    // Il comportamento di default da adoperare per memorizzare il valore
+    obj[prop] = newval;
+
+    // Indicate success
+    return true;
+  }
+});
+
+let i1 = view.selected = document.getElementById('item-1');
+console.log(i1.getAttribute('aria-selected')); // 'true'
+
+let i2 = view.selected = document.getElementById('item-2');
+console.log(i1.getAttribute('aria-selected')); // 'false'
+console.log(i2.getAttribute('aria-selected')); // 'true'
+ +

Value correction and an extra property

+ +

L'oggetto products  del proxy valuta il valore passato e lo converte in un array se è necessario. L'oggetto supporta anche una proprietà extra chiamata latestBrowser, uttilizzabile sia come getter che come setter.

+ +
let products = new Proxy({
+  browsers: ['Internet Explorer', 'Netscape']
+},
+{
+  get: function(obj, prop) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      return obj.browsers[obj.browsers.length - 1];
+    }
+
+    // Il comportamento di default per restituire il valore
+    return obj[prop];
+  },
+  set: function(obj, prop, value) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      obj.browsers.push(value);
+      return true;
+    }
+
+    // Converte il valore se non è un array
+    if (typeof value === 'string') {
+      value = [value];
+    }
+
+    // Il comportamento di default per memorizzare il valore
+    obj[prop] = value;
+
+    // Indicate success
+    return true;
+  }
+});
+
+console.log(products.browsers); // ['Internet Explorer', 'Netscape']
+products.browsers = 'Firefox'; // passa una stringa (per sbaglio)
+console.log(products.browsers); // ['Firefox'] <- nessun problema, il valore passato è un array
+
+products.latestBrowser = 'Chrome';
+console.log(products.browsers); // ['Firefox', 'Chrome']
+console.log(products.latestBrowser); // 'Chrome'
+ +

Trovare un oggetto in un array dalla sua proprietà

+ +

Questo proxy estende un array con alcune caratteristiche utiliti. Come puoi notare, puoi facilmente definire nuove proprietà senza utilizzare Object.defineProperties. Questo esempio può essere adattato per trovare una riga di una tabella partendo dalla sua cella. In questo caso il target sarà table.rows.

+ +
let products = new Proxy([
+  { name: 'Firefox', type: 'browser' },
+  { name: 'SeaMonkey', type: 'browser' },
+  { name: 'Thunderbird', type: 'mailer' }
+],
+{
+  get: function(obj, prop) {
+    // Il comportamento di default per ritornare un valore; prop è di solito un numero intero
+    if (prop in obj) {
+      return obj[prop];
+    }
+
+    // Ottieni il numero di prodotti; un alias di products.length
+    if (prop === 'number') {
+      return obj.length;
+    }
+
+    let result, types = {};
+
+    for (let product of obj) {
+      if (product.name === prop) {
+        result = product;
+      }
+      if (types[product.type]) {
+        types[product.type].push(product);
+      } else {
+        types[product.type] = [product];
+      }
+    }
+
+    // Ottieni un prodotto dal campo name
+    if (result) {
+      return result;
+    }
+
+    // Ottieni un prodotto dal campo type
+    if (prop in types) {
+      return types[prop];
+    }
+
+    // Ottieni i tipi di prodotto
+    if (prop === 'types') {
+      return Object.keys(types);
+    }
+
+    return undefined;
+  }
+});
+
+console.log(products[0]); // { name: 'Firefox', type: 'browser' }
+console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' }
+console.log(products['Chrome']); // undefined
+console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
+console.log(products.types); // ['browser', 'mailer']
+console.log(products.number); // 3
+
+ +

Una lista completa di traps

+ +

Adesso, per creare una lista di trappole, per scopi didattici, proveremo a proxare un oggetto non nativo che è particolarmente adatto a questo tipo di operazioni: l' oggetto globale docCookies creato da the "little framework" published on the document.cookie page.

+ +
/*
+  var docCookies = ... get the "docCookies" object here:
+  https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support
+*/
+
+var docCookies = new Proxy(docCookies, {
+  get: function (oTarget, sKey) {
+    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
+  },
+  set: function (oTarget, sKey, vValue) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.setItem(sKey, vValue);
+  },
+  deleteProperty: function (oTarget, sKey) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.removeItem(sKey);
+  },
+  enumerate: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  ownKeys: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  has: function (oTarget, sKey) {
+    return sKey in oTarget || oTarget.hasItem(sKey);
+  },
+  defineProperty: function (oTarget, sKey, oDesc) {
+    if (oDesc && 'value' in oDesc) { oTarget.setItem(sKey, oDesc.value); }
+    return oTarget;
+  },
+  getOwnPropertyDescriptor: function (oTarget, sKey) {
+    var vValue = oTarget.getItem(sKey);
+    return vValue ? {
+      value: vValue,
+      writable: true,
+      enumerable: true,
+      configurable: false
+    } : undefined;
+  },
+});
+
+/* Test dei cookie */
+
+console.log(docCookies.my_cookie1 = 'First value');
+console.log(docCookies.getItem('my_cookie1'));
+
+docCookies.setItem('my_cookie1', 'Changed value');
+console.log(docCookies.my_cookie1);
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ES2016', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità tra Browser

+ + + +

{{Compat("javascript.builtins.Proxy", 2)}}

+ +

Vedi anche

+ + + +

Nota di licenza

+ +

Alcuni contentui (test, esempi) in questa pagina sono stati copiati o adattatu dall' ECMAScript wiki i quali contenuti sono sotto licenza CC 2.0 BY-NC-SA.

diff --git a/files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html b/files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html new file mode 100644 index 0000000000..bf87d7e3e7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html @@ -0,0 +1,86 @@ +--- +title: Proxy.revocable() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/revocabile +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/revocable +--- +
{{JSRef}}
+ +

Il metodo Proxy.revocable() è usato per creare un oggetto {{jsxref("Proxy")}} revocabile.

+ +

Sintassi

+ +
Proxy.revocable(target, handler);
+
+ +

Parametri

+ +
{{ Page("it/docs/Web/JavaScript/Reference/Global_Objects/Proxy", "Parametri") }}
+ +

Valore restituito

+ +

Un nuovo oggetto Proxy revocabile.

+ +

Descrizione

+ +

Un Proxy revocabile è un oggetto con le seguenti due proprietà {proxy: proxy, revoke: revoke}.

+ +
+
proxy
+
L'oggetto Proxy creato con new Proxy(target, handler).
+
revoke
+
Una funzione che non richiede argomenti per disattivare il proxy.
+
+ +

Se la funzione revoke() viene invocata, il proxy diventa inutilizzabile: se si tenta di farne uso si otterrà un {{jsxref("TypeError")}}. Una volta che il proxy è revocato rimarrà in questo stato e potrà essere eliminato dal garbage collector. Successive invocazioni di revoke() non avranno effetto.

+ +

Esempi

+ +
var revocable = Proxy.revocable({}, {
+  get: function(target, name) {
+    return "[[" + name + "]]";
+  }
+});
+var proxy = revocable.proxy;
+console.log(proxy.foo); // "[[foo]]"
+
+revocable.revoke();
+
+console.log(proxy.foo); // viene sollevato un TypeError
+proxy.foo = 1           // viene sollevato un TypeError
+delete proxy.foo;       // viene sollevato un TypeError
+typeof proxy            // "object", typeof non innesca nessuna trappola
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy.revocable', 'Proxy Revocation Functions')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-proxy.revocable', 'Proxy Revocation Functions')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità tra Browser

+ + + +

{{Compat("javascript.builtins.Proxy.revocable")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/set/entries/index.html b/files/it/web/javascript/reference/global_objects/set/entries/index.html new file mode 100644 index 0000000000..367507d3d5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/set/entries/index.html @@ -0,0 +1,113 @@ +--- +title: Set.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Set/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Set/entries +--- +
{{JSRef}}
+ +

Il metodo entries() restituisce un novo oggetto Iterator che contiene un array di [valore, valore] per ciascun elemento nell'oggetto Set, nell'ordine con cui sono stati inseriti. Per gli oggetti di tipo Set non esiste alcuna chiave come per gli oggetti di tipo Map. Comunque, per mantenere le API simili a quelle dell'oggetto Map, per ciascun elemento dell'array viene utilizzato value anche per la chiave, perciò viene restituito un array [valore, valore].

+ +

Sintassi

+ +
mySet.entries()
+ +

Valore restituito

+ +

Un nuovo oggetto Iterator che contiene un array di [valore, valore] per ciascun elemento nell'oggetto Set, nell'ordine con cui sono stati inseriti.

+ +

Esempi

+ +

Uso di entries()

+ +
var mySet = new Set();
+mySet.add("foobar");
+mySet.add(1);
+mySet.add("baz");
+
+var setIter = mySet.entries();
+
+console.log(setIter.next().value); // ["foobar", "foobar"]
+console.log(setIter.next().value); // [1, 1]
+console.log(setIter.next().value); // ["baz", "baz"]
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommenti
{{SpecName('ES6', '#sec-set.prototype.entries', 'Set.prototype.entries')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.entries', 'Set.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support38{{ CompatGeckoDesktop("24") }}{{CompatNo}}257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}38{{ CompatGeckoMobile("24") }}{{CompatNo}}{{CompatNo}}8
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/set/index.html b/files/it/web/javascript/reference/global_objects/set/index.html new file mode 100644 index 0000000000..c8de5d83f6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/set/index.html @@ -0,0 +1,394 @@ +--- +title: Set +slug: Web/JavaScript/Reference/Global_Objects/Set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +
{{JSRef}}
+ +
L'oggetto Set permette di memorizzare valori unici di qualunque tipo, che siano {{Glossary("Primitive", "valori primitivi")}} o riferimenti ad oggetti.
+ +
 
+ +

Sintassi

+ +
new Set([iterabile]);
+ +

Parametri

+ +
+
iterabile
+
Se un oggetto iterabile è passato, tutti i suoi elementi saranno aggiunti al nuovo Set. null viene trattato come undefined.
+
+ +

Descrizione

+ +

Gli oggetti Set sono collezioni di valori, e possibile iterare i valori nel loro ordine di inserimento. Un valore in un Set può occorrere solo una volta; è quindi unico nella collezione.

+ +

Uguaglianza dei valori

+ +

Dato che ogni valore in un Set deve essere unico, dovra essere controllata l'uguaglianza di un nuovo valore con valori già presenti nel Set, questa operazione non è basata sullo stesso algoritmo usato per l'operatore ===. Nello specifico, per i Set, +0 (che è strettamente uguale a -0) e -0 sono valori differenti. Comunque, questo è stato cambiato nell'ultima specifica ECMAScript 6. Partendo da Gecko 29.0 {{geckoRelease("29")}} ({{bug("952870")}}) e da questa recente nightly Chrome issue, +0 e -0 sono trattati come valori identici nell'oggetto Set. Inoltre, NaN e undefined possono essere memorizzati nei Set. NaN è considerato unguale a NaN (anche se NaN !== NaN).

+ +

Proprietà

+ +
+
Set.size
+
Il valore della proprietà size è 0. 
+
{{jsxref("Set.@@species", "get Set[@@species]")}}
+
Il costruttore della funzione che viene usato per creare oggetti derivati.
+
{{jsxref("Set.prototype")}}
+
Rappresenta il prototipo per il costruttore del Set. Consente l'aggiunta di proprietà a tutti gli oggetti Set.
+
+ +

Instanze Set

+ +

Tutte le instanze di Set ereditano da {{jsxref("Set.prototype")}}.

+ +

Proprietà

+ +

{{page('it-IT/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}

+ +

Methods

+ +

{{page('it-IT/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}

+ +

Esempi

+ +

Uso dell'oggetto Set

+ +
var mySet = new Set();
+
+mySet.add(1);
+mySet.add(5);
+mySet.add("some text");
+var o = {a: 1, b: 2};
+mySet.add(o);
+
+mySet.has(1); // true
+mySet.has(3); // false, 3 non è stato aggiunto al set
+mySet.has(5);              // true
+mySet.has(Math.sqrt(25));  // true
+mySet.has("Some Text".toLowerCase()); // true
+mySet.has(o); // true
+
+mySet.size; // 4
+
+mySet.delete(5); // rimuove 5 dal set
+mySet.has(5);    // false, 5 è stato rimosso
+
+mySet.size; // 3, abbiamo rimosso 1 valore
+
+ +

Iterando oggetti Set

+ +
// iterando i valori in un set
+// logga gli item in ordine: 1, "testo di esempio"
+for (let item of mySet) console.log(item);
+
+// logga gli item in ordine: 1, "testo di esempio"
+for (let item of mySet.keys()) console.log(item);
+
+// logga gli item in ordine: 1, "testo di esempio"
+for (let item of mySet.values()) console.log(item);
+
+// logga gli item in ordine: 1, "testo di esempio"
+//(chiavi e valori qui sono uguali)
+for (let [key, value] of mySet.entries()) console.log(key);
+
+// converte un set in un Array semplice (con )
+// convert set to plain Array (con Array comprehensions)
+var myArr = [v for (v of mySet)]; // [1, "some text"]
+// Alternativa (con Array.from)
+var myArr = Array.from(mySet); // [1, "some text"]
+
+// Il seguente snippet funzionerà anche in un documento HTML
+mySet.add(document.body);
+mySet.has(document.querySelector("body")); // true
+
+// conversione tra Set e Array
+mySet2 = new Set([1,2,3,4]);
+mySet2.size; // 4
+[...mySet2]; // [1,2,3,4]
+
+// l'itersezione può essere simulata con
+var intersection = new Set([...set1].filter(x => set2.has(x)));
+
+// la differenza può essere simulata con
+var difference = new Set([...set1].filter(x => !set2.has(x)));
+
+// Itera i valori di un set con forEach
+mySet.forEach(function(value) {
+  console.log(value);
+});
+
+// 1
+// 2
+// 3
+// 4
+ +

Relazione con gli oggetti Array

+ +
var myArray = ["value1", "value2", "value3"];
+
+// Uso del costruttore di Set per trasformare un Array in un Set
+var mySet = new Set(myArray);
+
+mySet.has("value1"); // ritorna true
+
+// Usa l'operatore spread per trasformare un Set in un Array
+console.log(uneval([...mySet])); // Mostrerà lo stesso identico Array di myArray
+ +

Specifica

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-set-objects', 'Set')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{ CompatChrome(38) }} [1]

+
{{ CompatGeckoDesktop("13") }}{{ CompatIE("11") }}257.1
Constructor argument: new Set(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Set.clear(){{ CompatChrome(38) }}{{CompatGeckoDesktop("19")}}{{ CompatIE("11") }}257.1
Set.keys(), Set.values(), Set.entries(){{ CompatChrome(38) }}{{CompatGeckoDesktop("24")}}{{CompatNo}}257.1
Set.forEach(){{ CompatChrome(38) }}{{CompatGeckoDesktop("25")}}{{ CompatIE("11") }}257.1
Value equality for -0 and 0{{ CompatChrome(38) }}{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Set(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched add() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set() without new throws{{CompatUnknown}}{{CompatGeckoDesktop("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(38)}} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Set(iterable){{CompatNo}}{{CompatChrome(38)}}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Set.clear(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Set.keys(), Set.values(), Set.entries(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("24")}}{{CompatNo}}{{CompatNo}}8
Set.forEach(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Value equality for -0 and 0{{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Set(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched add() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] La caratteristica è disponibile come opzione da Chrome 31. In chrome://flags, attivare la voce “Enable Experimental JavaScript”.

+ +

Guarda pure

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

Il metodo values() restituisce un nuovo oggetto di tipo Iterator che contiene tutti i valori presenti nell'oggetto Set, nell'ordine con cui sono stati inseriti.

+ +

Il metodo keys() è un alias per questo metodo (in modo da mantenere api simili all'oggetto {{jsxref("Map")}}); si comporta esattamente allo stesss modo e restiuisce i valori contenuti nell'oggetto Set.

+ +

Sintassi

+ +
mySet.values();
+
+ +

Valore restituito

+ +

Un nuovo oggetto di tipo Iterator che contiene tutti i valori presenti nell'oggetto Set, nell'ordine con cui sono stati inseriti.

+ +

Esempi

+ +

Uso di values()

+ +
var mySet = new Set();
+mySet.add("foo");
+mySet.add("bar");
+mySet.add("baz");
+
+var setIter = mySet.values();
+
+console.log(setIter.next().value); // "foo"
+console.log(setIter.next().value); // "bar"
+console.log(setIter.next().value); // "baz"
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommenti
{{SpecName('ES6', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support38{{CompatGeckoDesktop("24")}}{{CompatNo}}257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}38{{ CompatGeckoMobile("24") }}{{ CompatNo}}{{ CompatNo}}8
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/charat/index.html b/files/it/web/javascript/reference/global_objects/string/charat/index.html new file mode 100644 index 0000000000..312cfa9713 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/charat/index.html @@ -0,0 +1,247 @@ +--- +title: String.prototype.charAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charAt +translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt +--- +
{{JSRef}}
+ +

Il metodo {{jsxref("String")}} dell'oggetto charAt() restituisce una nuova stringa che consiste nella singola unità di codice UTF-16 situata nell'offset specificato nella stringa.

+ +
{{EmbedInteractiveExample("pages/js/string-charat.html")}}
+ + + +

Sintassi

+ +
carattere = str.charAt(indice)
+ +

Parametri

+ +
+
index
+
Un numero intero compreso tra 0 e 1-meno della lunghezza della stringa. Se non viene fornito alcun indice, il valore predefinito è 0, quindi viene restituito il primo carattere nella stringa.
+
+ +

Valore restituito

+ +

Una stringa che rappresenta il carattere (esattamente un'unità di codice UTF-16) nell'indice specificato; stringa vuota se index non è compreso nell'intervallo

+ +

Descrizione

+ +

I caratteri in una stringa sono indicizzati da sinistra a destra. L'indice del primo carattere è 0 e l'indice dell'ultimo carattere in una stringa chiamata stringName è stringName.length - 1. Se l'indice che fornisci è fuori da questo intervallo, JavaScript restituisce una stringa vuota.

+ +

Se non viene fornito alcun indice per charAt(), il valore predefinito è 0.

+ +

Esempi

+ +

Visualizzazione di caratteri in posizioni diverse in una stringa

+ +

Nell'esempio seguente vengono visualizzati caratteri in posizioni diverse nella stringa "Brave new world":

+ +
var anyString = 'Brave new world';
+console.log("Il carattere nell'indice 0 è '" + anyString.charAt()   + "'");
+// Non è stato fornito alcun indice, usato 0 come predefinito
+
+console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
+console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
+console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
+console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
+console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
+console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
+
+ +

Queste righe mostrano quanto segue:

+ +
//Il carattere nell'indice 0   is 'B'
+
+//Il carattere nell'indice 0   is 'B'
+//Il carattere nell'indice 1   is 'r'
+//Il carattere nell'indice 2   is 'a'
+//Il carattere nell'indice 3   is 'v'
+//Il carattere nell'indice 4   is 'e'
+//Il carattere nell'indice 999 is ''
+
+ +

Recupero di caratteri interi

+ +

Quanto segue fornisce un mezzo per garantire che l'attraversamento di un loop string fornisca sempre un intero carattere, anche se la stringa contiene caratteri che non si trovano nel piano multi-lingue di base.

+ +
var str = 'A \uD87E\uDC04 Z'; // Potremmo anche usare direttamente un carattere non-BMP
+for (var i = 0, chr; i < str.length; i++) {
+  if ((chr = getWholeChar(str, i)) === false) {
+    continue;
+  }
+  // Adatta questa linea all'inizio di ogni ciclo, passando l'intera stringa e
+  // l'iterazione corrente e il ritorno di una variabile per rappresentare il
+  // personaggio individuale
+
+  console.log(chr);
+}
+
+function getWholeChar(str, i) {
+  var code = str.charCodeAt(i);
+
+  if (Number.isNaN(code)) {
+    return ''; // Posizione non trovata
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return str.charAt(i);
+  }
+
+  // Alto surrogato (potrebbe cambiare l'ultimo esadecimale a 0xDB7F per trattare un alto privato
+   // si surroga come singoli caratteri)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i + 1)) {
+      throw 'Alto surrogato senza seguire un surrogato basso';
+    }
+    var next = str.charCodeAt(i + 1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw 'Alto surrogato senza seguire un surrogato basso';
+      }
+      return str.charAt(i) + str.charAt(i + 1);
+  }
+  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw 'Basso surrogato senza precedente surrogato elevato';
+  }
+  var prev = str.charCodeAt(i - 1);
+
+  // (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw 'Basso surrogato senza precedente surrogato elevato';
+  }
+  // Ora possiamo passare sopra surrogati bassi come secondo componente
+   // in una coppia che abbiamo già elaborato
+  return false;
+}
+
+ +

In un ambiente ECMAScript 2016 che consente l'assegnazione destrutturata, la seguente è un'alternativa più succinta e un po 'più flessibile in quanto incrementa automaticamente una variabile incrementale (se il carattere lo richiede in quanto coppia surrogata).

+ +
var str = 'A\uD87E\uDC04Z'; // Potremmo anche usare direttamente un carattere non-BMP
+for (var i = 0, chr; i < str.length; i++) {
+  [chr, i] = getWholeCharAndI(str, i);
+  // Adatta questa linea all'inizio di ogni ciclo, passando l'intera stringa e
+  // l'iterazione corrente e la restituzione di un array con il singolo carattere
+  // e valore "i" (modificato solo se una coppia surrogata)
+
+  console.log(chr);
+}
+function getWholeCharAndI(str, i) {
+  var code = str.charCodeAt(i);
+  if (Number.isNaN(code)) {
+    return ''; // Posizione non trovata
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return [str.charAt(i), i]; // Carattere normale, mantenendo 'i' lo stesso
+  }
+  // Alto surrogato (potrebbe cambiare l'ultimo esadecimale a 0xDB7F per trattare un alto privato
+  // si surroga come singoli caratteri)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i + 1)) {
+      throw "Alto surrogato senza seguire un surrogato basso";
+    }
+    var next = str.charCodeAt(i + 1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw "Alto surrogato senza seguire un surrogato basso";
+      }
+      return [str.charAt (i) + str.charAt (i + 1), i + 1];
+  }
+  // Basso surrogato (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw "Basso surrogato senza precedente surrogato elevato";
+  }
+  var prev = str.charCodeAt(i - 1);
+  // (potrebbe cambiare l'ultimo esadecimale in 0xDB7F per trattare i surrogati ad alto livello privato
+  // come singoli caratteri)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw "Basso surrogato senza precedente surrogato elevato";
+  }
+  // Restituisce invece il carattere successivo (e incrementa)
+  return [str.charAt(i + 1), i + 1];
+}
+
+ +

Correggere charAt() per supportare caratteri non-Basic-Multilingual-Plane (BMP)

+ +

Mentre l'esempio sopra può essere più frequentemente utile per coloro che desiderano supportare caratteri non BMP (dal momento che non richiede al chiamante di sapere dove potrebbe apparire un personaggio non BMP), nel caso in cui uno lo desideri, nella scelta di un personaggio per indice, per trattare le coppie surrogate all'interno di una stringa come i singoli caratteri che rappresentano, si può usare quanto segue:

+ +
function fixedCharAt(str, idx) {
+  var ret = '';
+  str += '';
+  var end = str.length;
+
+  var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+  while ((surrogatePairs.exec(str)) != null) {
+    var li = surrogatePairs.lastIndex;
+    if (li - 2 < idx) {
+      idx++;
+    } else {
+      break;
+    }
+  }
+
+  if (idx >= end || idx < 0) {
+    return '';
+  }
+
+  ret += str.charAt(idx);
+
+ if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
+    // Vai avanti, poiché uno dei "personaggi" fa parte di una coppia di sostituti
+    ret += str.charAt(idx + 1);
+  }
+  return ret;
+}
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommenti
{{SpecName('ES1')}}{{Spec2('ES1')}}definizione iniziale.
{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ + + +

{{Compat("javascript.builtins.String.charAt")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/includes/index.html b/files/it/web/javascript/reference/global_objects/string/includes/index.html new file mode 100644 index 0000000000..44eac8fc22 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/includes/index.html @@ -0,0 +1,188 @@ +--- +title: String.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/String/includes +translation_of: Web/JavaScript/Reference/Global_Objects/String/includes +--- +
{{JSRef}}
+ +
Il metodo includes() verifica se una stringa ne contiene un'altra desiderata, restituendo truefalse in base dell'esito della ricerca.
+ +
 
+ +

Sintassi

+ +
str.includes(searchString[, position])
+ +

Parametri

+ +
+
searchString
+
Una stringa da cercare all'interno di una stringa.
+
position
+
Opzionale. La posizione in questa stringa. La posizione in questa stringa in cui iniziare la ricerca di searchString; il valore predefinito è 0.
+
+ +

Valore di ritorno

+ +

true se la stringa contiene la stringa di ricerca; altrimenti, false.

+ +

Descrizione

+ +

Questo metodo permette di determinare se la stringa includa o no un'altra stringa.

+ +

Sensitività alle maiuscole

+ +

Il metodo includes() è sensibile alle maiuscole. Per esempio, la seguente espressione restituisce false:

+ +
'Blue Whale'.includes('blue'); // returns false
+
+ +

Esempi

+ +

Utilizzando includes()

+ +
var str = 'To be, or not to be, that is the question.';
+
+console.log(str.includes('To be'));       // true
+console.log(str.includes('question'));    // true
+console.log(str.includes('nonexistent')); // false
+console.log(str.includes('To be', 1));    // false
+console.log(str.includes('TO BE'));       // false
+
+ +

Polyfill

+ +

Questo metodo è stato aggiunto alla specifica ECMAScript 2015 e potrebbe essere non disponibile ancora in tutte le implementazioni di JavaScript.

+ +
if (!String.prototype.includes) {
+  String.prototype.includes = function(search, start) {
+    'use strict';
+    if (typeof start !== 'number') {
+      start = 0;
+    }
+
+    if (start + search.length > this.length) {
+      return false;
+    } else {
+      return this.indexOf(search, start) !== -1;
+    }
+  };
+}
+
+/*
+https://github.com/FabioVergani/js-Polyfill_StringIncludes/blob/master/StringIncludes.js
+
+(function(s){'use strict';
+ var o=s.prototype,p='includes';
+ o[p]||(o[p]=function(a,b){//search,start
+  var e=this,i=isNaN(b)?0:b,t=a,l=t.length;
+  return (l<1||((i+l)>e.length))?false:-1!==e.indexOf(t,i);
+ });
+})(String);
+
+*/
+ +

 

+ +

 

+ +

 

+ +

 

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ES6')}}Definizioni inizili.
{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser 

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome("41")}}{{CompatGeckoDesktop("40")}}{{CompatNo}}14393+{{CompatNo}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("40")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

String.prototype.contains

+ +

In Firefox 18 - 39, il nome di questo metodo era contains(). E' stato rinominato inincludes() in {{bug(1102219)}} a causa del seguente motivo:

+ +

E' stato riportato che alcuni websites che utilizzano MooTools 1.2 non funzionavano su Firefox 17. Tale versione di MooTools controlla se String.prototype.contains() esiste e, se non esiste,  MooTools aggiunge una propria funzione. Con l'introduzione di questa funzione in Firefox 17, il comportamento di tale controllo è cambiato in un modo che il codice basato su String.prototype.contains()  non funzioni. Come risultato, l'implementazione  è stata disabilitata in Firefox 17 e String.prototype.contains() era disponibile nella versione successiva, in Firefox 18, quando outreach to MooTools stava conducendo al rilascio di MooTools version 1.2.6.

+ +

MooTools 1.3 forza la propria versione di  String.prototype.contains(), così i siti web che si affidano ad essa non vanno in break. Comunque si noti che la signature di  MooTools 1.3 e quella di ECMAScript 2015 per questo metodo differiscono (sul secondo argomento). Più avanti , MooTools 1.5+ ha cambiato la  signature per incontrare lo standard ES2015.

+ +

In Firefox 48, String.prototype.contains() è stato rimosso. Usare String.prototype.includes() solamente.

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/index.html b/files/it/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..713f9a0cb4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,410 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - NeedsTranslation + - Reference + - String + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

L'oggetto globale "String" è un costruttore per le stringhe o una sequenza alfanumerica di caratteri.

+ +

Syntax

+ +

String literals take the forms:

+ +
'string text'
+"string text"
+"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

Strings can also be created using the String global object directly:

+ +
String(thing)
+ +

Parametri

+ +
+
thing
+
Anything to be converted to a string.
+
+ +

Template literals

+ +

Starting with ECMAScript 2015, string literals can also be so-called Template literals:

+ +
`hello world`
+`hello!
+ world!`
+`hello ${who}`
+escape `<a>${who}</a>`
+ +
+
+ +

Escape notation

+ +

Beside regular, printable characters, special characters can be encoded using escape notation:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnuova linea
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
+ +
+

Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.

+
+ +
+
+ +

Long literal strings

+ +

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

+ +

You can use the + operator to append multiple strings together, like this:

+ +
let longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+
+ +

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

+ +
let longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+
+ +

Both of these result in identical strings being created.

+ +

Descrizione

+ +

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

+ +

Character access

+ +

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

+ +
return 'cat'[1]; // returns "a"
+
+ +

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

+ +

Comparing strings

+ +

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

+ +
var a = 'a';
+var b = 'b';
+if (a < b) { // true
+  console.log(a + ' is less than ' + b);
+} else if (a > b) {
+  console.log(a + ' is greater than ' + b);
+} else {
+  console.log(a + ' and ' + b + ' are equal.');
+}
+
+ +

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

+ +

Distinction between string primitives and String objects

+ +

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

+ +

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

+ +
var s_prim = 'foo';
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // Logs "string"
+console.log(typeof s_obj);  // Logs "object"
+
+ +

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

+ +
var s1 = '2 + 2';             // creates a string primitive
+var s2 = new String('2 + 2'); // creates a String object
+console.log(eval(s1));        // returns the number 4
+console.log(eval(s2));        // returns the string "2 + 2"
+
+ +

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

+ +

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
+ +

Properties

+ +
+
{{jsxref("String.prototype")}}
+
Allows the addition of properties to a String object.
+
+ +

Methods

+ +
+
{{jsxref("String.fromCharCode()")}}
+
Returns a string created by using the specified sequence of Unicode values.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
Returns a string created by using the specified sequence of code points.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
Returns a string created from a raw template string.
+
+ +

String generic methods

+ +
+

String generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser without using the shim that is provided below.

+
+ +

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

+ +
var num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

+ +

The following is a shim to provide support to non-supporting browsers:

+ +
/*globals define*/
+// Assumes all supplied String instance methods already present
+// (one may use shims for these if not available)
+(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(String).filter(function(methodName) {
+    //   return typeof String[methodName] === 'function';
+    // });
+    methods = [
+      'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
+      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
+      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
+      'toLocaleUpperCase', 'localeCompare', 'match', 'search',
+      'replace', 'split', 'substr', 'concat', 'slice'
+    ],
+    methodCount = methods.length,
+    assignStringGeneric = function(methodName) {
+      var method = String.prototype[methodName];
+      String[methodName] = function(arg1) {
+        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
+      };
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignStringGeneric(methods[i]);
+  }
+}());
+
+ +

String instances

+ +

Properties

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

Methods

+ +

Methods unrelated to HTML

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
+ +

HTML wrapper methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
+ +

Examples

+ +

String conversion

+ +

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, as although it still normally calls the underlying toString(), it also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatVersionUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/indexof/index.html b/files/it/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..e8653cac62 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,151 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +
{{JSRef}}
+ +

Il metodo indexOf() restituisce l'indice all'interno dell'oggetto {{jsxref("String")}} chiamante della prima occorrenza del valore specificato, avviando la ricerca su fromIndex. Restituisce -1 se il valore non viene trovato.

+ +
{{EmbedInteractiveExample("pages/js/string-indexof.html")}}
+ + + +
Note: Per il metodo dell'Array, vedere {{jsxref("Array.prototype.indexOf()")}}.
+ +

Sintassi

+ +
str.indexOf(searchValue[, fromIndex])
+ +

Parametri

+ +
+
searchValue
+
Una stringa che rappresenta il valore da cercare. Se non viene fornita esplicitamente alcuna stringa, searchValue sarà forzato a "undefined" e questo valore verrà cercato nella stringa corrente.
+
fromIndex {{optional_inline}}
+
Un numero intero che rappresenta l'indice al quale avviare la ricerca; il valore predefinito è  0. Per valori fromIndex values inferiori a 0 o maggiori di str.length, la ricerca inizia rispettivamente con 0str.length.
+
+ +

Valore di ritorno

+ +

L'indice della prima occorrenza di searchValue o -1 se non trovato.
+ Una stringa vuota searchValue corrisponderà a qualsiasi indice tra 0 e str.length.

+ +

Descrizione

+ +

I caratteri in una stringa sono indicizzati da sinistra a destra. L'indice del primo carattere è 0 e l'indice dell'ultimo carattere di una stringa chiamata stringName è stringName.length - 1.

+ +
'Blue Whale'.indexOf('Blue');     // ritorna  0
+'Blue Whale'.indexOf('Blute');    // ritorna -1
+'Blue Whale'.indexOf('Whale', 0); // ritorna  5
+'Blue Whale'.indexOf('Whale', 5); // ritorna  5
+'Blue Whale'.indexOf('Whale', 7); // ritorna -1
+'Blue Whale'.indexOf('');         // ritorna  0
+'Blue Whale'.indexOf('', 9);      // ritorna  9
+'Blue Whale'.indexOf('', 10);     // ritorna 10
+'Blue Whale'.indexOf('', 11);     // ritorna 10
+
+ +

Il metodo indexOf() è case sensitive. Ad esempio, la seguente espressione restituisce -1:

+ +
'Blue Whale'.indexOf('blue'); // ritorna -1
+
+ +

Controllo delle occorrenze

+ +

Nota che '0' non valuta true e '-1' non valuta false. Pertanto, quando si verifica se esiste una stringa specifica all'interno di un'altra stringa, il modo corretto per verificare sarebbe:

+ +
'Blue Whale'.indexOf('Blue') !== -1; // true
+'Blue Whale'.indexOf('Bloe') !== -1; // false
+
+ +

Esempi

+ +

Usare indexOf()

+ +

Nell'esempio seguente viene utilizzato indexOf() per individuare i valori nella stringa "Brave new world".

+ +
const str = 'Brave new world';
+
+console.log('L'indice della prima w dall'inizio è ' + str.indexOf('w'));  // logga 8
+console.log('L'indice di "new" dall'inizio è ' + str.indexOf('new'));  // logga 6
+
+ +

indexOf() e il case-sensitivity

+ +

L'esempio seguente definisce due variabili stringa. Le variabili contengono la stessa stringa tranne che la seconda stringa contiene lettere maiuscole. Il primo metodo {{domxref("console.log()")}} mostra 19. Ma poiché il metodo indexOf() è case sensitive, la stringa "cheddar" non si trova in myCapString, quindi il secondo metodo console.log() mostra -1.

+ +
const myString    = 'brie, pepper jack, cheddar';
+const myCapString = 'Brie, Pepper Jack, Cheddar';
+
+console.log('myString.indexOf("cheddar") è ' + myString.indexOf('cheddar'));
+// logs 19
+console.log('myCapString.indexOf("cheddar") è ' + myCapString.indexOf('cheddar'));
+// logs -1
+
+ +

Uso di indexOf() per contare le occorrenze di una lettera in una stringa

+ +

L'esempio seguente imposta count sul numero di occorrenze della lettera e nella stringa str:

+ +
const str = 'Essere o non essere, questa è la domanda.';
+let count = 0;
+let position = str.indexOf('e');
+
+while (position !== -1) {
+  count++;
+  position = str.indexOf('e', position + 1);
+}
+
+console.log(count); // mostra 4
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

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

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/length/index.html b/files/it/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..e575b777b8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,90 @@ +--- +title: string.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +
{{JSRef}}
+ +

La proprietà length di un oggetto {{jsxref("String")}} indica la lunghezza di una stringa, in unità di codice UTF-16.

+ +

Sintassi

+ +
str.length
+ +

Descrizione

+ +

Questa proprietà restituisce il numero di unità di codice nella stringa. {{interwiki("wikipedia", "UTF-16")}}, il formato di stringa utilizzato da JavaScript, utilizza una singola unità di codice a 16 bit per rappresentare i caratteri più comuni, ma deve utilizzare due unità di codice per meno comunemente- caratteri usati, quindi è possibile che il valore restituito dalla length “lunghezza“ non corrisponda al numero effettivo di caratteri nella stringa.

+ +

ECMASCript 2016 (ed. 7) ha stabilito una lunghezza massima di 2^53 - 1 elementi. In precedenza, non è stata specificata una lunghezza massima.. 

+ +

Per una stringa vuota, length è 0.

+ +

La proprietà statica String.length restituisce il valore 1.

+ +

Esempi

+ +

Basic usage

+ +
var x = 'Mozilla';
+var empty = '';
+
+console.log('Mozilla is ' + x.length + ' code units long');
+/* "Mozilla è lungo 7 unità di codice" */
+
+console.log('La stringa vuota ha una lunghezza di
+ ' + empty.length);
+/* "La stringa vuota ha una lunghezza di 0" */
+ +

Assegnazione a length

+ +
var myString = "bluebells";
+
+// Il tentativo di assegnare un valore alla proprietà .length di una stringa non ha alcun effetto osservabile.
+myString.length = 4;
+console.log(myString);
+/* "bluebells" */
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommenti
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale Implementato in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibili

+ + + +

{{Compat("javascript.builtins.String.length")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/prototype/index.html b/files/it/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..b13374a9a0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,178 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

La proprietà String.prototyperappresenta l'oggetto prototipo {{jsxref("String")}}.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Description

+ +

Tutte le istanze {{jsxref("String")}} ereditano da String.prototype . Le modifiche all'oggetto prototipo String vengono propagate a tutte le istanze {{jsxref("String")}}.

+ +

Properties

+ +
+
String.prototype.constructor
+
Specifica la funzione che crea il prototipo di un oggetto.
+
{{jsxref("String.prototype.length")}}
+
Riflette la lunghezza della stringa.
+
N
+
Utilizzato per accedere al carattere in N posizione in cui N è un numero intero positivo compreso tra 0 e uno inferiore al valore della {{jsxref("String.length", "length")}}. Queste proprietà sono di sola lettura.
+
+ +

Metodi

+ +

Metodi non correlati HTML

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
Restituisce il carattere (esattamente un'unità di codice UTF-16) all'indice specificato
+
{{jsxref("String.prototype.charCodeAt()")}}
+
Restituisce un numero che corrisponde al valore dell'unità di codice UTF-16 nell'indice specificato.
+
{{jsxref("String.prototype.codePointAt()")}}
+
Restituisce un numero intero non negativo Numero che è il valore del punto di codice codificato UTF-16 che inizia con l'indice specificato.
+
{{jsxref("String.prototype.concat()")}}
+
Combina il testo di due stringhe e restituisce una nuova stringa.
+
{{jsxref("String.prototype.includes()")}}
+
Determina se una stringa può essere trovata all'interno di un'altra stringa.
+
{{jsxref("String.prototype.endsWith()")}}
+
Determina se una stringa termina con i caratteri di un'altra stringa.
+
{{jsxref("String.prototype.indexOf()")}}
+
Restituisce l'indice all'interno dell'oggetto {{jsxref("String")}} chiamante della prima occorrenza del valore specificato o -1 se non trovato.
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
Restituisce l'indice all'interno dell'oggetto {{jsxref("String")}} chiamante della prima occorrenza del valore specificato o -1 se non trovato.
+
{{jsxref("String.prototype.localeCompare()")}}
+
Restituisce un numero che indica se una stringa di riferimento viene prima o dopo o è uguale alla stringa specificata in ordine di ordinamento.
+
{{jsxref("String.prototype.match()")}}
+
Utilizzato per abbinare un'espressione regolare a una stringa.
+
{{jsxref("String.prototype.normalize()")}}
+
Restituisce il modulo di normalizzazione Unicode del valore della stringa chiamante.
+
{{jsxref("String.prototype.padEnd()")}}
+
Riempie la stringa corrente dalla fine con una determinata stringa per creare una nuova stringa di una determinata lunghezza.
+
{{jsxref("String.prototype.padStart()")}}
+
Riempie la stringa corrente dall'inizio con una determinata stringa per creare una nuova stringa da una determinata lunghezza.
+
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
+
Avvolge la stringa tra virgolette (""").
+
{{jsxref("String.prototype.repeat()")}}
+
Restituisce una stringa composta da elementi dell'oggetto ripetuti i tempi indicati.
+
{{jsxref("String.prototype.replace()")}}
+
Utilizzato per trovare una corrispondenza tra un'espressione regolare e una stringa e per sostituire la sottostringa con corrispondenza con una nuova sottostringa.
+
{{jsxref("String.prototype.search()")}}
+
Esegue la ricerca di una corrispondenza tra un'espressione regolare e una stringa specificata.
+
{{jsxref("String.prototype.slice()")}}
+
Estrae una sezione di una stringa e restituisce una nuova stringa.
+
{{jsxref("String.prototype.split()")}}
+
Divide un oggetto  {{jsxref("Global_Objects/String", "String")}} in una matrice di stringhe separando la stringa in sottostringhe.
+
{{jsxref("String.prototype.startsWith()")}}
+
Determina se una stringa inizia con i caratteri di un'altra stringa.
+
{{jsxref("String.prototype.substr()")}} {{deprecated_inline}}
+
Restituisce i caratteri in una stringa che inizia nella posizione specificata attraverso il numero specificato di caratteri.
+
{{jsxref("String.prototype.substring()")}}
+
Restituisce i caratteri in una stringa tra due indici nella stringa.
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
I caratteri all'interno di una stringa vengono convertiti in minuscolo rispettando le impostazioni locali correnti. Per la maggior parte delle lingue, questo restituirà lo stesso di {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
I caratteri all'interno di una stringa vengono convertiti in maiuscolo rispettando le impostazioni locali correnti. Per la maggior parte delle lingue, ciò restituirà lo stesso di {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.
+
{{jsxref("String.prototype.toLowerCase()")}}
+
Restituisce il valore della stringa chiamante convertito in minuscolo.
+
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
+
Restituisce un oggetto letterale che rappresenta l'oggetto specificato; puoi usare questo valore per creare un nuovo oggetto. Sostituisce il metodo {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("String.prototype.toString()")}}
+
Restituisce una stringa che rappresenta l'oggetto specificato. Sostituisce il metodo {{jsxref("Object.prototype.toString()")}} .
+
{{jsxref("String.prototype.toUpperCase()")}}
+
Restituisce il valore della stringa chiamante convertito in maiuscolo.
+
{{jsxref("String.prototype.trim()")}}
+
Taglia gli spazi bianchi all'inizio e alla fine della stringa. Parte dello standard ECMAScript 5.
+
{{jsxref("String.prototype.trimStart()")}}
+ {{jsxref("String.prototype.trimLeft()")}}
+
Taglia gli spazi bianchi dall'inizio della stringa.
+
{{jsxref("String.prototype.trimEnd()")}}
+ {{jsxref("String.prototype.trimRight()")}}
+
Taglia gli spazi bianchi dalla fine della stringa.
+
{{jsxref("String.prototype.valueOf()")}}
+
Restituisce il valore primitivo dell'oggetto specificato. Sostituisce il metodo {{jsxref("Object.prototype.valueOf()")}}.
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}}
+
Restituisce un nuovo oggetto Iterator che itera sopra i punti di codice di un valore String, restituendo ogni punto di codice come valore String.
+
+ +

HTML metodi wrapper (involucro)

+ +

Questi metodi sono di uso limitato, in quanto forniscono solo un sottoinsieme dei tag e degli attributi HTML disponibili.

+ +
+
{{jsxref("String.prototype.anchor()")}} {{deprecated_inline}}
+
{{htmlattrxref("name", "a", "<a name=\"name\">")}} (hypertext target)
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}} {{deprecated_inline}}
+
{{htmlattrxref("href", "a", "<a href=\"url\">")}} (link to URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ + + +

{{Compat("javascript.builtins.String.prototype")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/raw/index.html b/files/it/web/javascript/reference/global_objects/string/raw/index.html new file mode 100644 index 0000000000..2d070b15cb --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/raw/index.html @@ -0,0 +1,108 @@ +--- +title: String.raw() +slug: Web/JavaScript/Reference/Global_Objects/String/raw +translation_of: Web/JavaScript/Reference/Global_Objects/String/raw +--- +
{{JSRef}}
+ +

Il metodo statico String.raw() è una funzione di tag del modello template string, simile al prefisso r in Python o al prefisso @ in C# per i valori letterali stringa (tuttavia c'è una differenza: vedere le spiegazioni in questo numero ). È usato per ottenere la stringa di stringhe di template non formattata, cioè le sostituzioni (ad esempio ${foo}) vengono elaborate, ma gli escape (ad esempio \n ) non lo sono.

+ +

Sintassi

+ +
String.raw(callSite, ...substitutions)
+String.raw`templateString`
+
+ +

Parametri

+ +
+
callSite
+
Oggetto del sito di chiamata template ben formato, come { raw: ['foo', 'bar', 'baz'] }.
+
...substitutions
+
Contiene valori di sostituzione.
+
templateString
+
A template string, puoi sostituirlo opzionalmente (${...}).
+
+ +

Valore resituto

+ +

Restituisce una stringa non elaborata di un determinato Template String.

+ +

Eccezioni

+ +
+
{{jsxref("TypeError")}}
+
Un oggetto {{jsxref("TypeError")}} viene generato se il primo argomento non è un oggetto formato.
+
+ +

Descrizione

+ +

Nella maggior parte dei casi, String.raw() viene utilizzato con template strings. La prima sintassi menzionata sopra è usata solo di rado, perché il motore JavaScript la chiamerà con argomenti appropriati, proprio come con altre funzioni tag .

+ +

String.raw() è l'unica funzione di built-in tag incorporata nei template strings; funziona proprio come la funzione predefinita del modello ed esegue la concatenazione. Puoi anche ri-implementarlo con il normale codice JavaScript.

+ +

Esempi

+ +

Utilizzo di String.raw()

+ +
String.raw`Ciao\n${2+3}!`;
+// 'Ciao\n5!', Il carattere dopo 'Ciao' non è un carattere di nuova riga,
+// '\' e 'n' sono due caratteri.
+
+String.raw`Hi\u000A!`;
+// 'Ciao\u000A!', Lo stesso qui, questa volta avremo il
+// \, u, 0, 0, 0, A, 6 caratteri.
+// Tutti i tipi di caratteri di escape saranno inefficaci
+// e backslash saranno presenti nella stringa di output
+// Puoi confermare questo controllando la proprietà .length
+// della stringa.
+
+let name = 'Bob';
+String.raw`Ciao\n${name}!`;
+// 'Ciao\nBob!', le sostituzioni vengono elaborate.
+
+// Normalmente non si chiama String.raw() come una funzione,
+// ma la si chiama per simulare `t${0}e${1}s${2}t` puoi fare:
+String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'
+// Nota che la stringa 'test', è un oggetto simile ad un array
+// Il seguente è equivalente a
+// `foo${2 + 3}bar${'Java' + 'Script'}baz`
+String.raw({
+  raw: ['foo', 'bar', 'baz']
+}, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommento
{{SpecName('ES2015', '#sec-string.raw', 'String.raw')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-string.raw', 'String.raw')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ + + +

{{Compat("javascript.builtins.String.raw")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/symbol/index.html b/files/it/web/javascript/reference/global_objects/symbol/index.html new file mode 100644 index 0000000000..5445a96009 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/symbol/index.html @@ -0,0 +1,230 @@ +--- +title: Symbol +slug: Web/JavaScript/Reference/Global_Objects/Symbol +tags: + - ECMAScript 2015 + - ECMAScript6 + - JavaScript + - Symbol +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +--- +
{{JSRef}}
+ +

La funzione Symbol() restituisce un valore di tipo symbol, dispone di proprietà statiche che espongono diversi membri di oggetti built-in, ha metodi statici che espongono il registro globale dei symbol, ed assomiglia all'oggetto built-in class, ma non dispone di un costruttore e non supporta la sintassi "new Symbol()".  

+ +

Ogni valore symbol restituito da Symbol() è unico.  Un valore symbol può essere utilizzato come identificatore per proprietà di un oggetto; questo è lo scopo di tale tipo di dati.  Ulteriori spiegazioni circa il loro scopo ed uso può essere trovato nella pagina: glossary entry for Symbol.

+ +

Il tipo di dati symbol è un {{Glossary("Primitive", "primitive data type")}}.

+ +

Syntax

+ +
Symbol([description])
+ +

Parametri

+ +
+
description {{optional_inline}}
+
Opzionale, string. Una descrizione del symbol che può essere usata per il debug ma non per accedere al symbol stesso.
+
+ +

Descrizione

+ +

Per creare un nuovo primitive symbol, scrivereSymbol() con una stringa opzionale di descrizione:

+ +
var sym1 = Symbol();
+var sym2 = Symbol('foo');
+var sym3 = Symbol('foo');
+
+ +

Il codice sopra crea tre nuovi symbol. Notare che Symbol("foo") non costringe la stringa "foo" in un symbol. Esso crea un nuovo symbol ogni volta:

+ +
Symbol('foo') === Symbol('foo'); // false
+ +

La sintassi seguente con l'operatore {{jsxref("Operators/new", "new")}} genererà un {{jsxref("TypeError")}}:

+ +
var sym = new Symbol(); // TypeError
+ +

Questo previene gli autori dal creare un esplicito oggetto wrapper Symbol invece di un nuovo valore symbol e la cosa può sorprendere in quanto creare un oggetto wrapper esplicito attorno ad un tipo di dati primitivo è generalmente possibile (ad esempio, new Boolean, new String e new Number).

+ +

Se veramente si vuole creare un oggetto wrapper Symbol si può usare la funzione Object():

+ +
var sym = Symbol('foo');
+typeof sym;     // "symbol"
+var symObj = Object(sym);
+typeof symObj;  // "object"
+
+ +

Symbols condivisi nel registro globale dei symbol

+ +

La sintassi vista sopra che utilizza la funzione Symbol() non crea un symbol globale che sarà disponibile nell'intero codebase. Per creare dei symbol disponibili attraverso diversi files ed anche attraverso diversi realms (ognuno dei quali ha il proprio global scope), usare i metodi {{jsxref("Symbol.for()")}} e {{jsxref("Symbol.keyFor()")}} per impostare e leggere i symbol dal registro globale.

+ +

Cercare le proprietà symbol negli oggetti

+ +

Il metodo {{jsxref("Object.getOwnPropertySymbols()")}} restituisce un array di symbol e permette di trovare le proprietà symbol di un oggetto. Notare che ogni oggetto è inizializzato senza alcuna proprietà symbol, per cui l'array restituito sarà vuoto a meno che una proprietà symbol non sia stata creata sull'oggetto.

+ +

Proprietà

+ +
+
Symbol.length
+
Proprietà "lunghezza", il cui valore è 0.
+
{{jsxref("Symbol.prototype")}}
+
Rappresenta il prototype del costruttore Symbol.
+
+ +

Symbols ben noti

+ +

In aggiunta ai symbol definiti da voi, JavaScript dispone di alcuni symbol built-in che rappresentano alcuni comportamenti interni del linguaggio che non sono esposti agli sviluppatori in ECMAScript5 e precedenti. A tali symbol si può accedere tramite le seguenti proprietà:

+ +

Symbols di iterazione

+ +
+
{{jsxref("Symbol.iterator")}}
+
Un metodo che restituisce l'iteratore di default per un oggetto. Usato da for...of.
+
{{jsxref("Symbol.asyncIterator")}} {{experimental_inline}}
+
Un metodo che restituisce l'iteratore asincrono di default per un oggetto. Usato da for await of.
+
+ +

Symbols per le espressioni regolari

+ +
+
{{jsxref("Symbol.match")}}
+
Un metodo che effettua la corrispondenza su una stringa, usato anche per determinare se un oggetto può essere utilizzato come espressione regolare. Usato da {{jsxref("String.prototype.match()")}}.
+
{{jsxref("Symbol.replace")}}
+
Un metodo che sostituisce le sottostringhe di una stringa corrispondenti. Usato da {{jsxref("String.prototype.replace()")}}.
+
{{jsxref("Symbol.search")}}
+
Un metodo che restituisce l'indice all'interno di una stringa che corrisponde all'espressione regolare. Usato da {{jsxref("String.prototype.search()")}}.
+
{{jsxref("Symbol.split")}}
+
Un metodo che divide una stringa all'indice corrispondente ad una espressione regolare. Usato da {{jsxref("String.prototype.split()")}}.
+
+ +

Altri symbols

+ +
+
{{jsxref("Symbol.hasInstance")}}
+
Un metodo che determina se un oggetto costruttore riconosce un oggetto come propria istanza. Usato da {{jsxref("Operators/instanceof", "instanceof")}}.
+
{{jsxref("Symbol.isConcatSpreadable")}}
+
Un valore booleano indicante se un oggetto deve essere appiattito ai soui elementi array. Usato da {{jsxref("Array.prototype.concat()")}}.
+
{{jsxref("Symbol.unscopables")}}
+
An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.
+
{{jsxref("Symbol.species")}}
+
Una funzione costruttore utilizzata per creare oggetti derivati.
+
{{jsxref("Symbol.toPrimitive")}}
+
Un metodo che converte un oggetto in un valore primitivo.
+
{{jsxref("Symbol.toStringTag")}}
+
Una stringa usata per la descizione di default di un oggetto. Usato da {{jsxref("Object.prototype.toString()")}}.
+
+ +

Metodi

+ +
+
{{jsxref("Symbol.for()", "Symbol.for(key)")}}
+
Cerca la "key" fornita tra i symbol esistenti e la restituisce nel caso in cui venga trovata. In caso contrario un nuovo symbol viene creato nel registro globale dei symbol con la "key" indicata.
+
{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}
+
Trova una chiave symbol condivisa dal registro globale dei symbol per il symbol fornito.
+
+ +

Symbol prototype

+ +

Tutti i simboli ereditano da {{jsxref("Symbol.prototype")}}.

+ +

Proprietà

+ +

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

+ +

Metodi

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}

+ +

Esempi

+ +

Using the typeof operator with symbols

+ +

L'operatore {{jsxref("Operators/typeof", "typeof")}} può aiutare ad identificare i symbol.

+ +
typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+ +

Conversioni di tipo dei symbol

+ +

Alcune cose da notare quando si lavora con le conversioni di tipo dei symbol.

+ + + +

Symbols ed iterazione for...in

+ +

I symbol non sono enumerabili in un'iterazione for...in. In aggiunta, {{jsxref("Object.getOwnPropertyNames()")}} non restituirà le proprietà symbol dell'oggetto, tuttavia, si puù usare {{jsxref("Object.getOwnPropertySymbols()")}} per ottenerle.

+ +
var obj = {};
+
+obj[Symbol('a')] = 'a';
+obj[Symbol.for('b')] = 'b';
+obj['c'] = 'c';
+obj.d = 'd';
+
+for (var i in obj) {
+   console.log(i); // logs "c" and "d"
+}
+ +

Symbols e JSON.stringify()

+ +

Le proprietà le cui chiavi sono symbol vengono completamente ignorate da JSON.stringify():

+ +
JSON.stringify({[Symbol('foo')]: 'foo'});
+// '{}'
+ +

Per ulteriori dettagli, vedere {{jsxref("JSON.stringify()")}}.

+ +

Symbol wrapper objects come chiavi per le proprietà

+ +

Quando un oggetto wrapper symbol viene usato come chiave di una proprietà, tale oggetto verrà costretto al suo wrapped symbol:

+ +
var sym = Symbol('foo');
+var obj = {[sym]: 1};
+obj[sym];            // 1
+obj[Object(sym)];    // still 1
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificazioneStatoCommento
{{SpecName('ES2015', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ES2015')}}Initial definition
{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Symbol")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/undefined/index.html b/files/it/web/javascript/reference/global_objects/undefined/index.html new file mode 100644 index 0000000000..d16ca712cf --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/undefined/index.html @@ -0,0 +1,173 @@ +--- +title: undefined +slug: Web/JavaScript/Reference/Global_Objects/undefined +translation_of: Web/JavaScript/Reference/Global_Objects/undefined +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La variabile globale undefined rappresenta il valore primitivo {{Glossary("Undefined", "undefined")}}. È uno dei {{Glossary("Primitive", "valori primitivi")}} di JavaScript.

+ +

{{js_property_attributes(0,0,0)}}

+ +

Sintassi

+ +
undefined
+ +

Descrizione

+ +

undefined è una proprietà dell'oggetto globale, ossia una variablie nel contesto globale. Il valore iniziale di undefined è il valore primitivo {{Glossary("Undefined", "undefined")}}.

+ +

Secondo la specifica ECMAScript5, undefined è accessibile in sola lettura (implementato in JavaScript 1.8.5 / Firefox 4).

+ +

Una variabile alla quale non è ancora stato assegnato un valore è di tipo undefined. Un metodo o una dichiarazione restituisce undefined se la variabile che viene valutata non ha un valore assegnato. Una funzione restituisce undefined se non viene restituito un altro valore.

+ +

Siccome undefined non è una {{jsxref("Reserved_Words", "parola riservata")}}, può essere usato come nome di una variabile in qualsiasi contesto, eccetto quello globale.

+ +
// logs "foo string"
+(function(){ var undefined = 'foo'; console.log(undefined, typeof undefined); })();
+
+// logs "foo string"
+(function(undefined){ console.log(undefined, typeof undefined); })('foo');
+
+ +

Esempi

+ +

undefined e l'uguaglianza ristretta

+ +

Puoi usare undefined e gli operatori "strettamente uguale" e "strettamente diverso" per determinare se ad una variabile è stato assegnato un valore. In questo codice, la variabile x non è definita, qundi l'istruzione if viene valutata vera.

+ +
var x;
+
+x === undefined; // true
+
+ +
Nota: Qui devono essere utilizzati gli operatori di uguaglianza stretta, perché x == undefined è vero anche se x è null, mentre confrontandoli con l'ugualianza stretta no. null e undefined non sono equivalenti. Vedi gli {{jsxref("Operators/Comparsion_Operators", "operatori di comparazione")}} per altri dettagli.
+ +

undefined e l'operatore typeof

+ +

In alternativa può anche essere usato l'operatore {{jsxref("Operators/typeof", "typeof")}}:

+ +
var x;
+
+typeof x === 'undefined'; // true
+
+ +

Un motivo per cui usare l'operatore {{jsxref("Operators/typeof", "typeof")}} è che se la variabile non  stata dichiarata non viene generato un errore.

+ +
// x non è ancora stata dichiarata
+
+typeof x === "undefined"; // viene valutata come vera, senza generare erroi
+
+x === undefined;          // genera un ReferenceError
+
+ +

Comunque questa tecnica dovrebbe essere evitata. JavaScript è un linguaggio staticamente contestualizzato, quindi si può sapere se una variabile è stata dichiarata in un contesto guardando in quelli che lo contengono. L'unica eccezione è il contesto globale, che è rappresentato dall'oggetto globale: quindi per sapere se esiste una variabile basta controllare se esiste una proprietà nell'oggetto globale (per esempio usando l'operatore {{jsxref("Operators/in", "in")}} o il metodo {{jsxref("Global_Objects/Object/hasOwnProperty", "hasOwnProperty")}})

+ +
// x non è ancora stata dichiarata
+
+"x" in window;              // false
+window.hasOwnProperty("x"); // false
+
+var x = 3;
+
+"x" in window;              // true
+window.hasOwnProperty("y"); // true
+
+ +

undefined e l'operatore void

+ +

Una terza alternativa è l'operatore {{jsxref("Operators/void", "void")}}.

+ +
var x;
+x === void 0; // true
+
+// y non è ancora stata dichiarata
+y === void 0; // genera un ReferenceError (a differenza di `typeof`)
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardDefinizione iniziale. Implementato in JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.3', 'undefined')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-undefined', 'undefined')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/unescape/index.html b/files/it/web/javascript/reference/global_objects/unescape/index.html new file mode 100644 index 0000000000..d3c31d5f96 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/unescape/index.html @@ -0,0 +1,124 @@ +--- +title: unescape() +slug: Web/JavaScript/Reference/Global_Objects/unescape +translation_of: Web/JavaScript/Reference/Global_Objects/unescape +--- +
+
+
{{jsSidebar("Objects")}} {{deprecated_header()}}
+
+
+ +

Sommario

+ +

La funzione unescape(), deprecata, crea una nuova stringa nella quale le sequenze di escape esadecimali vengono sostituite con il loro carattere corrispondente. Le sequenze di escape potrebbero essere state generate da funzioni simili a {{jsxref("Global_Objects/escape", "escape()")}}. Essendo unescape() deprecata, è preferibile utilizzare le funzioni {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} o {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}.

+ +
Nota: Non usare la funzione unescape() per decodificare degli {{Glossary("URI")}}, usa {{jsxref("Global_Objects/decodeURI", "decodeURI()")}}.
+ +

Sintassi

+ +
unescape(string)
+ +

Parametri

+ +
+
string
+
La stringa da decodificare.
+
+ +

Descrizione

+ +

La funzione unescape() è una proprietà dell'oggetto globale.

+ +

Esempi

+ +
unescape("abc123");     // "abc123"
+unescape("%E4%F6%FC");  // "äöü"
+unescape("%u0107");     // "ć"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-B.2.2', 'unescape')}}{{Spec2('ES5.1')}}Definita nell'appendice B, "Compatibility"
{{SpecName('ES6', '#sec-unescape-string', 'unescape')}}{{Spec2('ES6')}}Definita nell'appendice B, "Additional ECMAScript Features for Web Browsers"
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/uneval/index.html b/files/it/web/javascript/reference/global_objects/uneval/index.html new file mode 100644 index 0000000000..965dc014b4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/uneval/index.html @@ -0,0 +1,112 @@ +--- +title: uneval() +slug: Web/JavaScript/Reference/Global_Objects/uneval +translation_of: Web/JavaScript/Reference/Global_Objects/uneval +--- +
+
+
{{jsSidebar("Objects")}}{{Non-standard_header}}
+
+
+ +

Sommario

+ +

La funzione uneval() crea una stringa rappresentante il codice sorcente di un oggetto.

+ +

Sintassi

+ +
uneval(object)
+ +

Parametri

+ +
+
object
+
Una qualsiasi espressione o dichiarazione JavaScript
+
+ +
Nota: Questa funzione non restituisce una rappresentazione JSON valida. Usare il metodo {{jsxref("JSON.stringify()")}}
+ +

Descrizione

+ +

uneval() è una funzione globale e non è associata a nessun oggetto.

+ +

Esempi

+ +
var a = 1;
+uneval(a); // restituisce la stringa "1"
+
+var b = "1";
+uneval(b) // restituisce la stringa '"1"'
+
+uneval(function foo(){}); // restituisce "(function foo(){})"
+
+
+var a = uneval(function foo(){return "ciao"});
+var foo = eval(a);
+foo(); // restituisce "ciao"
+
+ +

Specifiche

+ +

Non fa parte di nessuna specifica.

+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Vedi anche

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