diff options
Diffstat (limited to 'files/it/web/javascript/reference/global_objects')
127 files changed, 0 insertions, 21221 deletions
diff --git a/files/it/web/javascript/reference/global_objects/array/concat/index.html b/files/it/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index 9d8d7d6629..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -tags: - - Array - - aggiungi elementi array - - concat -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>concat()</strong></code> ritorna un nuovo array costituito dall'array sul quale è stato invocato (joined array) e dagli array e/o valori passati come argomenti.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">var <var>new_array</var> = <var>old_array</var>.concat(<var>value1</var>[, <var>value2</var>[, ...[, <var>valueN</var>]]])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>value<em>N</em></code></dt> - <dd>Array e/o valori da concatenare nel nuovo array. Vedere la descrizione sotto per i dettagli.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Una nuova istanza di {{jsxref("Array")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>concat</code> 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.</p> - -<p>Il metodo <code>concat</code> non altera l'oggetto <code>this</code> (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:</p> - -<ul> - <li>Riferimenti agli oggetti (non gli oggetti stessi): <code>concat</code> copia nel nuovo array i riferimenti agli oggetti. Sia gli elementi degli array originali che quelli dell'array prodotto da concat puntano agli stessi oggetti. Pertanto, se uno degli oggetti cui i riferimenti puntano viene cambiato, i cambiamenti possono essere visualizzati tramite i riferimenti contenuti nell'array originale o nella copia. Ciò include gli elementi degli argomenti di tipo array che fossero array a loro volta.</li> -</ul> - -<pre class="brush: js">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} -</pre> - -<ul> - <li>Tipi di dati come stringhe, numeri e booleani (non oggetti {{jsxref("Global_Objects/String", "String")}}, {{jsxref("Global_Objects/Number", "Number")}}, e {{jsxref("Global_Objects/Boolean", "Boolean")}} ): <code>concat</code> li copia per valore nel nuovo array.</li> -</ul> - -<div class="note"> -<p><strong>Note:</strong> 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.</p> -</div> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Concatenare_due_array">Concatenare due array</h3> - -<h3 id="Il_codice_seguente_concatena_due_array"><span style="font-size: 14px;">Il codice seguente concatena due array:</span></h3> - -<pre class="brush: js">var alpha = ['a', 'b', 'c']; -var numeric = [1, 2, 3]; - -alpha.concat(numeric); -// Risultato: ['a', 'b', 'c', 1, 2, 3] -</pre> - -<h3 id="Concatenare_tre_array">Concatenare tre array</h3> - -<p>Il codice seguente concatena tre array:</p> - -<pre class="brush: js">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] -</pre> - -<h3 id="Concatenare_valori_ad_un_array">Concatenare valori ad un array</h3> - -<p>Il codice seguente concatena dei valori a quelli presenti in un array:</p> - -<pre class="brush: js">var alpha = ['a', 'b', 'c']; - -var alphaNumeric = alpha.concat(1, [2, 3]); - -console.log(alphaNumeric); -// Risultato: ['a', 'b', 'c', 1, 2, 3] -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Definizione iniziale, implementato in JavaScript 1.2.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_Browser">Compatibilità con i Browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Browser</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto Base</td> - <td>{{CompatChrome("1.0")}}</td> - <td>{{CompatGeckoDesktop("1.7")}}</td> - <td>{{CompatIE("5.5")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Browser</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Supporto Base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — aggiunge/rimuove elementi dalla fine di un array</li> - <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — aggiunge/rimuove elementi dall'inizio di un array</li> - <li>{{jsxref("Array.splice", "splice")}} — aggiunge/rimuove elementi da una posizione specifica dell'array</li> - <li>{{jsxref("String.prototype.concat()")}}</li> - <li>{{jsxref("Symbol.isConcatSpreadable")}} – control flattening.</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/copywithin/index.html b/files/it/web/javascript/reference/global_objects/array/copywithin/index.html deleted file mode 100644 index 65e00abe47..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/copywithin/index.html +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: Array.prototype.copyWithin() -slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin -translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>copyWithin()</strong></code> copia superficialmente una parte di un array in un'altra locazione dello stesso array e lo restituisce, senza modificare la sua dimensione.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}</div> - -<p class="hidden">Il codice sorgente di questo esempio interattivo e' reperibile in una repository di GitHub. Se sei interessato nel contribuire agli esempi interattivi, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> ed inviaci una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.copyWithin(<var>target</var>) -<var>arr</var>.copyWithin(<var>target</var>, <var>start</var>) -<var>arr</var>.copyWithin(<var>target</var>, <var>start</var>, <var>end</var>) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>target</code></dt> - <dd>Indice zero-based fino al quale copiare la sequenza. Se negativo, <code>target</code> sarà impostato all'ultimo elemento dell'array.</dd> - <dd>Se <code>target</code> è pari o più grande di <code>arr.length</code>, non sarà copiato nulla. Se <code>target</code> è posizionato dopo <code>start</code>, la sequenza copiata, sarà ritagliata per poter rientrare in <code>arr.length</code>.</dd> - <dt><code>start</code> {{optional_inline}}</dt> - <dd>Indice zero-based dal quale si comincia a copiare gli elementi. Se negativo, <code>start</code> comincerà a contare dalla fine.</dd> - <dd>Se <code>start</code> è omesso, <code>copyWithin</code> copierà dall'inizio (default 0).</dd> - <dt><code>end</code> {{optional_inline}}</dt> - <dd>Indice zero-based che indica l'ultimo indice dal quale copiare. <code>copyWithin</code> copia fino ad <code>end</code> ma non lo include. Se negativo, <code>end</code> sarà contato dalla fine.</dd> - <dd>Se <code>end</code> è omesso, <code>copyWithin</code> copierà fino alla fine (default <code>arr.length</code>).</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'array modificato.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>copyWithin</code> ha le stesse funzionalità di <code>memmove</code> 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.</p> - -<p>La funzione <code>copyWithin</code> è intenzionalmente<em> generic</em>, e non richiede che i suoi argomenti siano {{jsxref("Array")}} object.</p> - -<p><code>copyWithin</code> è un metodo mutabile. Non altera la lunghezza di <code>this</code>, ma cambia il suo contenuto e crea nuove proprietà se necessario..</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">[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] -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<pre><code>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; - } -</code> -<code> // 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; - }; -}</code></pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES2016', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> - <td>{{Spec2('ES2016')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div> -<div class="hidden">La tabella di compatibilità in questa pagina è generata mediante dati strutturati. Se vuoi contribuire ai dati, controlla <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> ed inviaci una pull request.</div> - -<p>{{Compat("javascript.builtins.Array.copyWithin")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/entries/index.html b/files/it/web/javascript/reference/global_objects/array/entries/index.html deleted file mode 100644 index 31e156afb8..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/entries/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Array.prototype.entries() -slug: Web/JavaScript/Reference/Global_Objects/Array/entries -translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>entries()</strong></code> restituisce un nuovo oggetto <code><strong>Array Iterator</strong></code> contenente delle coppie chiave/valore per ogni indice presente nell'array.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-entries.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>a</var>.entries()</pre> - -<h3 id="Valore_ritornato">Valore ritornato</h3> - -<p>Un nuovo oggetto iterator {{jsxref("Array")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzo_nel_for…of">Utilizzo nel <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for…of</a></h3> - -<pre class="brush:js">var a = ['a', 'b', 'c']; -var iterator = a.entries(); - -for (let e of iterator) { - console.log(e); -} -// [0, 'a'] -// [1, 'b'] -// [2, 'c'] -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_il_browser">Compatibilità con il browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.entries")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.keys()")}}</li> - <li>{{jsxref("Array.prototype.values()")}}</li> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>{{jsxref("Array.prototype.every()")}}</li> - <li>{{jsxref("Array.prototype.some()")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/every/index.html b/files/it/web/javascript/reference/global_objects/array/every/index.html deleted file mode 100644 index c1f3238ad6..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/every/index.html +++ /dev/null @@ -1,184 +0,0 @@ ---- -title: Array.prototype.every() -slug: Web/JavaScript/Reference/Global_Objects/Array/every -translation_of: Web/JavaScript/Reference/Global_Objects/Array/every ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>every()</strong></code> controlla che tutti gli elementi all'interno dell'array passino il test implementato dalla funzione fornita.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-every.html")}}</div> - -<p class="hidden">Il codice sorgente per questo esempio interattivo è salvato all'interno di una repository GitHub. Se vuoi contribuire al progetto sugli esempi interattivi, perfavore clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e mandaci una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.every(<var>callback</var>[, <var>thisArg</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione da testare per ciascun elemento, che prende tre argomenti: - <dl> - <dt><code>currentValue</code> (required)</dt> - <dd>L'elemento corrente che viene elaborato all'interno dell'array.</dd> - <dt><code>index</code>{{Optional_inline}}</dt> - <dd>L'indice dell'elemento corrente che viene elaborato all'interno dell'array.</dd> - <dt><code>array</code>{{Optional_inline}}</dt> - <dd>L'array <code>every</code> chiamato.</dd> - </dl> - </dd> - <dt><code>thisArg</code>{{Optional_inline}}</dt> - <dd>Opzionale. Valore da utilizzare come <code>this</code> durante l'esecuzione della <code>callback</code>.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p><code><strong>true</strong></code> se la funzione callback ritorna un valore {{Glossary("truthy")}} per ciascun elemento dell'array; altrimenti, <code><strong>false</strong></code>.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>every</code> esegue la funzione <code>callback</code> fornita una volta per ciascun elemento presente all'interno dell'array finché non ne trova uno per il quale la <code>callback</code> ritorna un valore {{Glossary("falsy")}}. Altrimenti, se la <code>callback</code> ritorna un valore {{Glossary("truthy")}} per tutti gli elementi, <code>every</code> ritorna <code>true</code>. <code>callback</code> 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.</p> - -<p><code>callback</code> viene invocata con tre argomenti: il valore dell'elemento, l'indice dell'elemento, e l'Array oggetto che viene attraversato. </p> - -<p>Se il parametro <code>thisArg</code> viene fornito a <code>every</code>, esso verrà usato come valore <code>this</code> per la <code>callback</code>. Altrimenti, il valore <code>undefined</code> verrà usato al suo posto come valore <code>this</code>. Il valore <code>this</code>, ultimo osservabile dalla <code>callback</code>, viene determinato secondo <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">le usuali regole per determinare il this visto da una funzione.</a></p> - -<p><code>every</code> non modifica l'array in cui viene chiamato.</p> - -<p>Il range di elementi processati da <code>every</code> viene impostato prima della prima invocazione di <code>callback</code>. Gli elementi che vengono appesi all'inizio dell'array dopo la chiamata a <code>every</code> non verranno visitati dalla <code>callback</code>. Se gli elementi esistenti dell'array vengono cambiati, il loro valore passato a <code>callback</code> sarà il valore al momento in cui <code>every</code> li visiterà; gli elementi cancellati non sono visitati.</p> - -<p><code>every</code> agisce come il quantificatore "for all" in matematica. In particolare, per un array vuoto, esso ritorna true. (E' <a href="http://en.wikipedia.org/wiki/Vacuous_truth#Vacuous_truths_in_mathematics">vacuously true</a> che tutti gli elementi dell' <a href="http://en.wikipedia.org/wiki/Empty_set#Common_problems">empty set</a> soddisfano qualsiasi condizione data.)</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Controllo_sulla_grandezza_di_tutti_gli_elementi_dell'array">Controllo sulla grandezza di tutti gli elementi dell'array</h3> - -<p>Il seguente esempio controlla che tutti gli elementi dell'array siano maggiori di 10.</p> - -<pre class="brush: js">function isBigEnough(element, index, array) { - return element >= 10; -} -[12, 5, 8, 130, 44].every(isBigEnough); // false -[12, 54, 18, 130, 44].every(isBigEnough); // true -</pre> - -<h3 id="Utilizzando_arrow_functions">Utilizzando arrow functions</h3> - -<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> forniscono una sintassi più breve per lo stesso test.</p> - -<pre class="brush: js">[12, 5, 8, 130, 44].every(x => x >= 10); // false -[12, 54, 18, 130, 44].every(x => x >= 10); // true</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>every</code> è 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 <code>every</code> in implementazioni che non lo supportano nativamente. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo che <code>Object</code> e <code>TypeError</code> abbiano i loro valori originali e che <code>callbackfn.call</code> valuti sul valore originale di {{jsxref("Function.prototype.call")}}.</p> - -<pre class="brush: js">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; - }; -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.every")}}</p> -</div> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>{{jsxref("Array.prototype.some()")}}</li> - <li>{{jsxref("TypedArray.prototype.every()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/fill/index.html b/files/it/web/javascript/reference/global_objects/array/fill/index.html deleted file mode 100644 index 043696f554..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/fill/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Array.prototype.fill() -slug: Web/JavaScript/Reference/Global_Objects/Array/fill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>fill()</strong></code> assegna un valore statico a tutti gli elementi di un array compresi tra un indice iniziale ed un indice finale.</p> - -<pre class="brush: js">var numbers = [1, 2, 3] -numbers.fill(1); - -// results in [1, 1, 1]</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.fill(<var>value</var><var><var>)</var></var> -<var>arr</var>.fill(<var>value</var>, <var>start<var>) -</var>arr</var>.fill(<var>value</var>, <var>start<var>, <var>end</var>)</var></var> -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>value</code></dt> - <dd>Valore statico da assegnare agli elementi dell'array.</dd> - <dt><code>start</code> {{optional_inline}}</dt> - <dd>Indice iniziale, default uguale a 0.</dd> - <dt><code>end</code> {{optional_inline}}</dt> - <dd>Indice finale, default uguale a <code>this.length</code>.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'array modificato.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>L'intervallo di elementi da assegnare è compreso tra [<code>start</code>, <code>end</code>).</p> - -<p>Il metodo <strong><code>fill</code></strong> accetta fino a tre argomenti: <code>value</code>, <code>start</code> and <code>end</code>. Gli argomenti <code>start</code> e <code>end</code> sono opzionali con valori di default rispettivamente di <code>0</code> di <code>length</code> dell'oggetto <code>this</code> .</p> - -<p>Se <code>start</code> è negativo, viene interpretato come <code>length+start</code> dove <code>length</code> è la lunghezza dell'array. Se <code>end</code> è negativo, viene intrpretato come <code>length+end</code>.</p> - -<p>La funzione <strong><code>fill</code></strong> è volutamente generica, non richiede che il suo valore <code>this</code> sia un Array.</p> - -<p>Il metodo <strong><code>fill</code></strong> è mutabile, ovvero modifica l'oggetto <code>this</code> e lo restituisce modificato, ovvero non ne restituisce una copia modificata.</p> - -<p>Quando al metodo <strong><code>fill</code></strong> viene passato un oggetto, il metodo effettuerà una copia dell'oggetto e assegnerà agli elementi dell'Array un riferimento alla copia.</p> - -<h2 id="Examples">Examples</h2> - -<pre class="brush: js">[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" }] -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<pre class="brush: js">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; - } - }); -} -</pre> - -<p>Se hai necessità di supportare engine Javascript veramente obsolete che non supportano <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, è meglio non usare affatto il polyfill per il medoto <code>Array.prototype</code> perchè non è possibile renderlo non enumerabile.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.fill")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array")}}</li> - <li>{{jsxref("TypedArray.prototype.fill()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/filter/index.html b/files/it/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 33d24d38b6..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>filter() </strong></code>crea un nuovo array contentente tutti gli elementi che passano il test implementato dalla funzione. </p> - -<pre class="brush: js">function isBigEnough(value) { - return value >= 10; -} - -var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); -// filtered is [12, 130, 44] -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>var new_array = arr</var>.filter(<var>callback</var>[, <var>thisArg</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione predicato per testare ciascun elemento dell'array. Restituisce <code>true</code> se l'elemento va mantenuto, <code>false</code> altrimenti. Essa prende in input tre argomenti:</dd> - <dd> - <dl> - <dt><code>element</code></dt> - <dd>L'elemento corrente nell'array processato.</dd> - <dt><code>index</code></dt> - <dd>L' indice dell'elemento corrente processato nell'array.</dd> - <dt><code>array</code></dt> - <dd>l'array su cui <code>filter</code> è stato chiamato.</dd> - </dl> - </dd> - <dt><code>thisArg</code></dt> - <dd>Opzionale. Valore da usare come <code>this</code> quando si esegue <code>callback</code>.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Un nuovo array con gli elementi che hanno passato il test.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>filter()</code> chiama funzione ricorsiva (<code>callback</code>) fornita una volta per ciascun elemento dell'array e crea un nuovo array con tutti quei valori in cui la <code>callback</code> ha restituito un valore<a href="/en-US/docs/Glossary/Truthy"> <code>true</code></a>.. <code>callback</code> 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.</p> - -<p><code>callback</code> viene invocata con tre argomenti:</p> - -<ol> - <li>il valore dell'elemento</li> - <li>l'indice dell'elemento</li> - <li>l' Array oggetto da passare</li> -</ol> - -<p>Se viene fornito a <code>filter</code> un parametro <code>thisArg</code> , questo verrà passato a sua volta a <code>callback</code> quando verrà invocata per usarlo come valore di <code>this</code> . Altrimenti verrà passato un valore <code>undefined</code> per essere usato come valore di <code>this</code>. Il valore <code>this</code> osservabile in definitiva dalla funzione <code>callback</code> viene scelto seguendo <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">le usuali regole di determinazione dei <code>this </code>visti da una funzione</a>.</p> - -<p><code>filter()</code> non muta l'array sul quale viene chiamata.</p> - -<p>La gamma di element processati da <code>filter()</code> viene impostata prima della invocazione della <code>callback</code>. Gli elementi che vengono mesi nell'array da filtrare dopo l'invocazione di <code>filter()</code> non verranno esaminati dalla <code>callback</code>. Se ci sono elementi dell'array da fitrare i cui valori vengono cambiati o vengono cancellati dopo la applicazione di <code>filter()</code> , questi nel tempo di chamata di <code>filter()</code> verranno testati dalla <code>callback</code> nello stato previo alla loro modifica. Elementi cancellati prima della applicazione di <code>filter()</code> non vengono visitati.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Filtrare_tutti_i_piccoli_valori">Filtrare tutti i piccoli valori</h3> - -<p>Il seguente esempio usa <code>filter()</code> per realizzare un array filtrato che non contenga elementi di valore inferiore a 10.</p> - -<pre class="brush: js">function isBigEnough(value) { - return value >= 10; -} - -var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); -// filtered is [12, 130, 44] -</pre> - -<h3 id="Filtrare_entrate_non_valide_in_JSON">Filtrare entrate non valide in JSON</h3> - -<p>Il sequente esempio di utilizzo di <code>filter()</code> crea un json filtrato di elementi con valido id numerico.</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>filter()</code> è 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 <code>filter()</code> nelle implementazioni ECMA-262 che non lo supportanto nativamente. Questo algoritmo è esattamente quello nella specifica ECMA-262, quinta edizione, assumendo che <code>fn.call</code> valuti il valore originale di {{jsxref("Function.prototype.call()")}},e che {{jsxref("Array.prototype.push()")}} abbia il suo valore originale.</p> - -<pre class="brush: js">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; - }; -} -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> - <p>Definizione iniziale. Implementato in javascript 1.6.</p> - </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("1.8")}}</td> - <td>{{CompatIE("9")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("1.8")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>{{jsxref("Array.prototype.every()")}}</li> - <li>{{jsxref("Array.prototype.some()")}}</li> - <li>{{jsxref("Array.prototype.reduce()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/find/index.html b/files/it/web/javascript/reference/global_objects/array/find/index.html deleted file mode 100644 index c215ff79e7..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/find/index.html +++ /dev/null @@ -1,216 +0,0 @@ ---- -title: Array.prototype.find() -slug: Web/JavaScript/Reference/Global_Objects/Array/find -tags: - - Array - - ECMAScript 2015 - - ECMAScript6 - - JavaScript - - Prototype - - Riferimento - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/find ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>find()</strong></code> restituisce il <strong>valore</strong> del primo elemento nell'array che soddisfi la funzione di test passata come argomento. Altrimenti viene restituito {{jsxref("undefined")}}.</p> - -<pre class="brush: js">function isBigEnough(element) { - return element >= 15; -} - -[12, 5, 8, 130, 44].find(isBigEnough); // 130</pre> - -<p>Vedi anche il metodo {{jsxref("Array.findIndex", "findIndex()")}}, che restituisce l'<strong>indice</strong> dell'elemento trovato nell'array invece del suo valore.</p> - -<p>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()")}}.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.find(<var>callback</var>[, <var>thisArg</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione da eseguire per ogni valore contenuto nell'array, richiede tre argomenti: - <dl> - <dt><code>element</code></dt> - <dd>L'elemento nell'array che dev'essere testato.</dd> - <dt><code>index</code></dt> - <dd>L'indice dell'elemento nell'array che dev'essere testato.</dd> - <dt><code>array</code></dt> - <dd>L'array sul quale è stato chiamato il <code>find</code>.</dd> - </dl> - </dd> - <dt><code>thisArg</code></dt> - <dd>Opzionale. L'oggetto da utilizzare come <code>this</code> durante l'esecuzione della <code>callback</code>.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Un valore dell'array se un elemento soddisfa la condizione; altrimenti, {{jsxref("undefined")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>find</code> esegue la funzione di <code>callback</code> una sola volta per ciascun elemento nell'array finché non ne trova uno per il quale la funzione di <code>callback</code> restituisca <code>true</code>. Se tale elemento viene trovato, <code>find</code> restituisce immediatamente il valore di quell'elemento. Altrimenti, <code>find</code> restituisce {{jsxref("undefined")}}. La funzione <code>callback</code> è 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.</p> - -<p>Alla funzione <code>callback</code> vengono passati tre parametri: il valore dell'elemento, l'indice dell'elemento e l'oggetto Array che si sta esplorando.</p> - -<p>Se viene passato il parametro <code>thisArg</code> al metodo <code>find</code>, questo verrà usato come <code>this</code> per ciascuna invocazione della funzione <code>callback</code>. Altrimenti viene utilizzato {{jsxref("undefined")}}.</p> - -<p>Il metodo <code>find</code> non modifica l'array sul quale viene chiamato.</p> - -<p>L'intervallo di elementi analizzati dal metodo <code>find</code> è impostato prima della prima invocazione della <code>callback</code>. Gli elementi aggiunti all'array successivamente alla chiamata del metodo <code>find</code> non verranno analizzate dalla <code>callback</code>. Se un elemento dell'array esistente, ma non ancora visitato, viene modificato dalla <code>callback</code>, il valore passato alla funzione <code>callback</code> sarà il valore contenuto nel momento in cui il metodo <code>find</code> visita l'indice di quell'elemento; gli elementi eliminati non vengono visitati.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Trova_un_oggetto_in_un_array_tramite_una_sua_proprietà">Trova un oggetto in un array tramite una sua proprietà</h3> - -<pre class="brush: js">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 }</pre> - -<h3 id="Trova_un_numero_primo_in_un_array">Trova un numero primo in un array</h3> - -<p>L'esempio seguente trova un elemento nell'array che sia un numero primo (o restituisce {{jsxref("undefined")}} se non ce ne sono).</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>Questo metodo è stato aggiunto nella specifica ECMAScript 2015 e potrebbe non ancora essere disponibile in tutte le implementazioni JavaScript. Comunque, puoi aggiungere il metodo <code>Array.prototype.find()</code> utilizzando il seguente snippet:</p> - -<pre class="brush: js">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; - } - }); -} -</pre> - -<p>Se hai la necessità di supportare motori JavaScript molto obsoleti che non supportano <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, sarebbe meglio non aggiungere per niente il metodo <code>Array.prototype.find()</code>, poiché potresti renderli non-enumerabili.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Edge</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatChrome(45.0)}}</td> - <td>{{CompatGeckoDesktop("25.0")}}</td> - <td>{{CompatNo}}</td> - <td>12</td> - <td>{{CompatOpera(32.0)}}</td> - <td>{{CompatSafari("7.1")}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Edge</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatGeckoMobile("25.0")}}</td> - <td>{{CompatNo}}</td> - <td>12</td> - <td>{{CompatNo}}</td> - <td>8.0</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.findIndex()")}}</li> - <li>{{jsxref("Array.prototype.every()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/findindex/index.html b/files/it/web/javascript/reference/global_objects/array/findindex/index.html deleted file mode 100644 index f9f2f65791..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/findindex/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Array.prototype.findIndex() -slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex -translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex ---- -<div>{{JSRef}}</div> - -<p><span class="seoSummary">Il metodo <code><strong>findIndex()</strong></code> restituisce l'<strong>indice</strong> del primo elemento nell'array <strong>che soddisfa la funzione di testing fornita</strong>. Altrimenti, restituisce <code>-1</code>, indicando che nessun elemento ha superato il test.</span></p> - -<div>{{EmbedInteractiveExample("pages/js/array-findindex.html","shorter")}}</div> - -<div class="hidden">Il sorgente di questo esempio interattivo è salvato una repository GitHub. Se volessi contribuire al progetto degli esempi interattivi, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and inviaci una pull request.</div> - -<p>Guarda anche il metodo {{jsxref("Array.find", "find()")}}, che restituisce il <strong>valore</strong> dell'elemento anziché il suo indice.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox notranslate"><var>arr</var>.findIndex(<var>callback</var>( <var>elemento</var>[,<em>indice</em>[, <var>array</var>]] )[, <var>thisArg</var>]) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code><var>callback</var></code></dt> - <dd> - <p>Una funzione da eseguire su ognuno dei valori finché la funzione non resitituisce <code>true</code>, indicando che l'elemento che soddisfa la condizione è stato trovato.</p> - - <p>Prende in input tre argomenti:</p> - - <dl> - <dt><code><var>elemento</var></code></dt> - <dd>L'elemento dell'array che viene processato.</dd> - <dt><code><var>indice</var></code> {{optional_inline}}</dt> - <dd>L'indice dell'elemento dell'array che viene processato.</dd> - <dt><code><var>array</var></code> {{optional_inline}}</dt> - <dd>L'array su cui è stato chiamato <code>findIndex()</code>.</dd> - </dl> - </dd> - <dt><code><var>thisArg</var></code> {{optional_inline}}</dt> - <dd>Oggetto da usare come <code>this</code> quando viene eseguita la <code><var>callback</var></code>.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>L'indice dell primo elemento dell'array che supera il test. Altrimenti <code>-1</code>.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Il metodo </span></font>findIndex()</code> esegue la <code><var>callback</var></code> una volta per ogni indice nell'array finché non trova quello per cui la <code><var>callback</var></code> ritorna un valore {{Glossary("truthy")}}.</p> - -<p>Se l'elemento viene trovato, <code>findIndex()</code> restitutisce immediatamente l'idice dell'elemento. Se <code><var>callback</var></code> non restituisce mai un valore {{Glossary("truthy")}} (o la <code>length</code> dell'array è <code>0</code>), <code>findIndex()</code> restituisce <code>-1</code>.</p> - -<div class="blockIndicator note"> -<p><strong>Caso limite: </strong>A differenza di altri metodi per array come {{jsxref("Array.some()")}}, <code><var>callback</var></code> viene eseguita anche per gli indici con valori non assegnati.</p> -</div> - -<p><code><var>callback</var></code> è invocata con tre argomenti:</p> - -<ol> - <li>Il valore dell'elemento</li> - <li>L'indice dell'elemento</li> - <li>L'oggetto Array che viene percorso</li> -</ol> - -<p>Se viene passato a <code>findIndex()</code> un parametro <code><var>thisArg</var></code>, sarà usato come <code>this</code> in ogni invocazione di <code><var>callback</var></code>. Se non viene passato si usa {{jsxref("undefined")}}.</p> - -<p>The range of elements processed by <code>findIndex()</code> is set before the first invocation of <code><var>callback</var></code>. <code><var>callback</var></code> will not process the elements appended to the array after the call to <code>findIndex()</code> begins. If an existing, unvisited element of the array is changed by <code><var>callback</var></code>, its value passed to the <code><var>callback</var></code> will be the value at the time <code>findIndex()</code> visits the element's index.</p> - -<p>Elements that are <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">deleted</a> are still visited.</p> - -<h2 id="Polyfill">Polyfill</h2> - -<pre class="brush: js notranslate">// 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 - }); -} -</pre> - -<p>If you need to support truly obsolete JavaScript engines that do not support {{jsxref("Object.defineProperty")}}, it is best not to polyfill <code>Array.prototype</code> methods at all, as you cannot make them non-enumerable.</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Find_the_index_of_a_prime_number_in_an_array">Find the index of a prime number in an array</h3> - -<p>The following example returns the index of the first element in the array that is a prime number, or <code>-1</code> if there is no prime number.</p> - -<pre class="brush: js notranslate">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) -</pre> - -<h3 id="Find_index_using_arrow_function">Find index using arrow function</h3> - -<p>The following example finds the index of a fruit using an arrow function:</p> - -<pre class="brush: js notranslate">const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; - -const index = fruits.findIndex(fruit => fruit === "blueberries"); - -console.log(index); // 3 -console.log(fruits[index]); // blueberries -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.findIndex")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Array.prototype.find()")}}</li> - <li>{{jsxref("Array.prototype.indexOf()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/flat/index.html b/files/it/web/javascript/reference/global_objects/array/flat/index.html deleted file mode 100644 index 3c5a81ed4b..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/flat/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Array.prototype.flat() -slug: Web/JavaScript/Reference/Global_Objects/Array/flat -tags: - - Array - - JavaScript - - Prototype - - Referenza - - flat - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat ---- -<div></div> - -<div>{{JSRef}}</div> - -<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Il metodo </span></font><strong>flat()</strong></code> crea un nuovo array con tutti gli elementi dei propri sotto-array concatenati ricorsivamente al suo interno fino alla profondità specificata.</p> - -<p class="hidden">\{{EmbedInteractiveExample("pages/js/array-flatten.html")}}</p> - -<p class="hidden">Il codice sorgente per questo esempio interattivo è mantenuto in una repository GitHub. Se vuoi contribuire al progetto degli esempi interattivi, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviaci una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox notranslate"><var>var newArray = arr</var>.flat(<em>[profondità]</em>);</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">profondità</span></font> {{optional_inline}}</dt> - <dd>Il livello di profondità che specifica quanto a fondo la struttura di array annidati deve essere appianata. Default a 1.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un nuovo array con gli elementi dei sotto-array concatenati al suo interno.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Appianare_array_annidati">Appianare array annidati</h3> - -<pre class="brush: js notranslate">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] -</pre> - -<h3 id="Appianamento_e_slot_vuoti_negli_array">Appianamento e slot vuoti negli array</h3> - -<p>Il metodo flat rimuove gli slot vuoti in un array:</p> - -<pre class="brush: js notranslate">var arr4 = [1, 2, , 4, 5]; -arr4.flat(); -// [1, 2, 4, 5] -</pre> - -<h2 id="Alternative">Alternative</h2> - -<h3 id="reduce_e_concat"><code>reduce</code> e <code>concat</code></h3> - -<pre class="brush: js notranslate">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); -</pre> - -<pre class="brush: js notranslate">//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] -</pre> - -<pre class="brush: js notranslate">//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] -</pre> - -<pre class="brush: js notranslate">//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; -} -</pre> - -<div class="hidden"> -<p>Per favore, non aggiungere polyfill a questo articolo. Per referenze, controllare: <a href="https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500">https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500</a></p> -</div> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td> - <p><a href="https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flat"><code>Array.prototype.flat</code> proposal</a></p> - </td> - <td>Finished (4)</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> -<div class="hidden">La tabella di compatibilità in questa pagina è generata da dati strutturati. Per favore controlla <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e mandaci una pull request se vuoi contribuire.</div> - -<p>{{Compat("javascript.builtins.Array.flat")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.flatMap()")}}</li> - <li>{{jsxref("Array.prototype.map()")}}</li> - <li>{{jsxref("Array.prototype.reduce()")}}</li> - <li>{{jsxref("Array.prototype.concat()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/flatmap/index.html b/files/it/web/javascript/reference/global_objects/array/flatmap/index.html deleted file mode 100644 index 4397fd7c5d..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/flatmap/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Array.prototype.flatMap() -slug: Web/JavaScript/Reference/Global_Objects/Array/flatMap -translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>flatMap()</strong></code> 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 <code>flatMap()</code> in questo caso è la soluzione migliore perché è più efficente delle due chiamate separate.</p> - -<p class="hidden">{{EmbedInteractiveExample("pages/js/array-flatmap.html")}}</p> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox notranslate"><var>var new_array = arr</var>.flatMap(function <var>callback(currentValue[, index[, array]]) { - // restituisci un elemento per il nuovo array -}</var>[, <var>thisArg</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione per produrre un elemento del nuovo Array, prevede a sua volta tre parametri: - <dl> - <dt></dt> - <dt><code>currentValue</code></dt> - <dd>L'elemento che si sta processando.</dd> - <dt><code>index</code>{{optional_inline}}</dt> - <dd>L'indice dell'elemento corrente.</dd> - <dt><code>array</code>{{optional_inline}}</dt> - <dd>L'array che si sta processando con <code>map</code>.</dd> - </dl> - </dd> - <dt><code>thisArg</code>{{optional_inline}}</dt> - <dd>Valore usato come <code>this</code> mentre si esegue la <code>callback</code>.</dd> -</dl> - -<h3 id="Risultato">Risultato</h3> - -<p>Un nuovo array i cui elementi sono il risultato della chiamata a <code>callback</code>, "appiattiti" ad una profondità di 1</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Guarda {{jsxref("Array.prototype.map()")}} per una descrizione dettagliata della funzione <code>callback</code>. <code>flatMap</code> è identico a una chiamata a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a></code> seguita da una chiamata <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat">flat</a></code> con una profondità di 1.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="map_e_flatMap"><code>map()</code> e <code>flatMap()</code></h3> - -<pre class="brush: js notranslate">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]] -</pre> - -<p>Lo stesso risultato lo si può ottenere anche con la sola chiamata a map, di seguito è riportato un esempio migliore di uso di <code>flatMap</code>.</p> - -<p>Viene generata una lista di parole da una lista di frasi.</p> - -<pre class="brush: js notranslate">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"]</pre> - -<p>Notare che, a differenza di map da solo, la lunghezza dell'output è diversa tra le due chiamate e in particolare il risultato di <code>flatMap</code> non avrà la stessa lunghezza dell'input.</p> - -<h3 id="Aggiungere_e_rimuovere_elementi_durante_lesecuzione_di_map">Aggiungere e rimuovere elementi durante l'esecuzione di <code>map()</code></h3> - -<p><code>flatMap</code> può essere usato per aggiungere e rimuovere elementi durante l'esecuzione di <code>map</code>. In altre parole, offre la possibilità di mappare <em>molti a molti</em> (processando ogni input separatamente), anziché sempre <em>uno a uno</em>. In questo senso lavora come opposto di <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter</a>. 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.</p> - -<pre class="brush: js notranslate">// 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] -</pre> - -<h2 id="Alternative">Alternative</h2> - -<h3 id="reduce_and_concat"><code>reduce()</code> and <code>concat()</code></h3> - -<pre class="brush: js notranslate">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] -</pre> - -<p>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 (<code>acc</code>), in un nuovo array ad ogni iterazione invece di aggiungerli ad uno preesistente.</p> - -<div class="hidden"> -<p>Please do not add polyfills on this article. For reference, please check: <a href="https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500">https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500</a></p> -</div> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.flatmap', 'Array.prototype.flatMap')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.flatMap")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.flat()")}}</li> - <li>{{jsxref("Array.prototype.map()")}}</li> - <li>{{jsxref("Array.prototype.reduce()")}}</li> - <li>{{jsxref("Array.prototype.concat()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/foreach/index.html b/files/it/web/javascript/reference/global_objects/array/foreach/index.html deleted file mode 100644 index dbd4919852..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/foreach/index.html +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Array.prototype.forEach() -slug: Web/JavaScript/Reference/Global_Objects/Array/forEach -tags: - - Array - - ECMAScript 5 - - JavaScript - - Prototype - - Referenza - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>forEach()</strong></code> esegue una funzione fornita una volta per ogni elemento dell'array.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.forEach(<var>callback(currentValue [, index [, array]])</var>[, <var>thisArg</var>]);</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione da eseguire per ciascun elemento, prendendo tre argomenti:</dd> - <dd> - <dl> - <dt><code>currentValue</code></dt> - <dd>L'elemento corrente in elaborazione nell'array.</dd> - <dt><code>index</code> {{optional_inline}}</dt> - <dd>L'indice dell'elemento corrente in elaborazione nell'array.</dd> - <dt><code>array</code> {{optional_inline}}</dt> - <dd>L'array a cui viene applicato <code>forEach()</code>.</dd> - </dl> - </dd> - <dt><code>thisArg</code> {{optional_inline}}</dt> - <dd>Valore da utilizzare come <code>this</code> quando si esegue <code>callback</code>.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>forEach()</code> esegue il <code>callback</code> fornito una volta per ciascun elemento presente nell'array in ordine crescente. Non è invocato per le proprietà dell'indice che sono state eliminate o non inizializzate (ad esempio su array sparsi).</p> - -<p><code>callback</code> viene invocato con tre argomenti:</p> - -<ul> - <li>il valore dell'elemento</li> - <li>l'indice dell'elemento</li> - <li>l'array che deve essere iterato</li> -</ul> - -<p>Se viene fornito il parametro <code>thisArg</code> a <code>forEach()</code>, verrà utilizzato come valore <code>this</code> del callback. Altrimenti, il valore {{jsxref("undefined")}} sarà usato come valore <code>this</code>. Il valore <code>this</code> alla fine osservabile da <code>callback</code> è determinato secondo <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">le consuete regole per determinare il <code>this</code> visto da una funzione</a>.</p> - -<p>L'intervallo di elementi elaborati da <code>forEach()</code> viene impostato prima della prima chiamata del <code>callback</code>. Gli elementi aggiunti all'array dopo che la chiamata <code>forEach()</code> inizia non saranno calcolati da <code>callback</code>. Se i valori degli elementi esistenti dell'array vengono modificati, il valore passato a <code>callback</code> sarà il valore al momento in cui <code>forEach()</code> li visita; gli elementi che vengono cancellati prima di essere visitati non vengono visitati. Se gli elementi già visitati vengono rimossi (ad esempio usando {{jsxref("Array.prototype.shift()", "shift()")}}) durante l'iterazione, gli elementi successivi verranno saltati - vedi l'esempio sotto.</p> - -<p><code>forEach()</code> esegue la funzione <code>callback</code> una volta per ogni elemento dell'array; a differenza di {{jsxref("Array.prototype.map()", "map()")}} o {{jsxref("Array.prototype.reduce()", "reduce()")}} restituisce sempre {{jsxref("undefined")}} e non è concatenabile. Il tipico caso d'uso è eseguire effetti collaterali alla fine del chain.</p> - -<p><code>forEach()</code> non muta l'array su cui è chiamato (sebbene <code>callback</code>, se invocato, possa farlo).</p> - -<div class="note"> -<p>Non c'è modo di fermare o interrompere un loop <code>forEach()</code> se non lanciando un'eccezione. Se hai bisogno di un simile comportamento, il metodo <code>forEach()</code> è lo strumento sbagliato.</p> - -<p>La risoluzione anticipata può essere eseguita con:</p> - -<ul> - <li>Un loop semplice</li> - <li>Un loop <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></li> - <li>{{jsxref("Array.prototype.every()")}}</li> - <li>{{jsxref("Array.prototype.some()")}}</li> - <li>{{jsxref("Array.prototype.find()")}}</li> - <li>{{jsxref("Array.prototype.findIndex()")}}</li> -</ul> - -<p>Gli altri metodi per array: {{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.find()")}}, e {{jsxref("Array.prototype.findIndex()")}} testano gli elementi dell'array con un predicato restituendo un valore di verità per determinare se è necessaria un'ulteriore iterazione.</p> -</div> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Convertire_un_loop_for_in_forEach">Convertire un loop for in forEach</h3> - -<pre class="brush:js">const items = ['item1', 'item2', 'item3']; -const copy = []; - -// prima -for (let i=0; i<items.length; i++) { - copy.push(items[i]); -} - -// dopo -items.forEach(function(item) { - copy.push(item); -}); -</pre> - -<h3 id="Stampa_del_contenuto_di_un_array">Stampa del contenuto di un array</h3> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> Per visualizzare il contenuto di un array nella console, puoi utilizzare <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/table">console.table()</a></code> che stamperà una versione formattata dell'array. L'esempio seguente illustra un altro modo per farlo, usando <code>forEach()</code>.</p> -</div> - -<p>Il seguente codice logga una linea per ogni elemento in un array:</p> - -<pre class="brush:js">function logArrayElements(element, index, array) { - console.log('a[' + index + '] = ' + element); -} - -// Nota che l'indice 2 viene saltato poiché non vi è alcun elemento -// in quella posizione nell'array. -[2, 5, , 9].forEach(logArrayElements); -// logga: -// a[0] = 2 -// a[1] = 5 -// a[3] = 9 -</pre> - -<h3 id="Usare_thisArg">Usare <code>thisArg</code></h3> - -<p>Il seguente esempio (inventato) aggiorna le proprietà di un oggetto da ciascuna voce dell'array:</p> - -<pre class="brush:js">function Counter() { - this.sum = 0; - this.count = 0; -} -Counter.prototype.add = function(array) { - array.forEach(function(entry) { - this.sum += entry; - ++this.count; - }, this); - // ^---- Nota -}; - -const obj = new Counter(); -obj.add([2, 5, 9]); -obj.count; -// 3 -obj.sum; -// 16 -</pre> - -<p>Poiché il parametro <code>thisArg</code> (<code>this</code>) viene fornito a <code>forEach()</code>, viene passato a <code>callback</code> ogni volta che viene richiamato, per essere utilizzato come valore <code>this</code>.</p> - -<div class="note"> -<p>Se si passa l'argomento della funzione utilizzando <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">un'espressione della funzione a freccia</a> il parametro <code>thisArg</code> può essere omesso poiché le funzioni a freccia associano in modo lessicale il valore {{jsxref("Operators/this", "this")}}.</p> -</div> - -<h3 id="Una_funzione_di_copia_di_oggetti">Una funzione di copia di oggetti</h3> - -<p>Il seguente codice crea una copia di un dato oggetto. Esistono diversi modi per creare una copia di un oggetto; il seguente è solo un modo e viene presentato per spiegare come funziona <code>Array.prototype.forEach()</code> usando le funzioni di meta proprietà ECMAScript 5 <code>Object.*</code>.</p> - -<pre class="brush: js">function copy(obj) { - const copy = Object.create(Object.getPrototypeOf(obj)); - const propNames = Object.getOwnPropertyNames(obj); - - propNames.forEach(function(name) { - const desc = Object.getOwnPropertyDescriptor(obj, name); - Object.defineProperty(copy, name, desc); - }); - - return copy; -} - -const obj1 = { a: 1, b: 2 }; -const obj2 = copy(obj1); // obj2 looks like obj1 now -</pre> - -<h3 id="Se_l'array_viene_modificato_durante_l'iterazione_altri_elementi_potrebbero_essere_saltati.">Se l'array viene modificato durante l'iterazione, altri elementi potrebbero essere saltati.</h3> - -<p>L'esempio seguente registra "uno", "due", "quattro". Quando viene raggiunta la voce contenente il valore "due", la prima voce dell'intero array viene spostata, il che comporta il trasferimento di tutte le voci rimanenti in una posizione. Poiché l'elemento "quattro" è ora in una posizione precedente nell'array, "tre" verrà saltato. <code>forEach()</code> non esegue una copia dell'array prima di iterare.</p> - -<pre class="brush:js">var words = ['uno', 'due', 'tre', 'quattro']; -words.forEach(function(word) { - console.log(word); - if (word === 'due') { - words.shift(); - } -}); -// uno -// due -// quattro -</pre> - -<h3 id="Appiattire_un_array">Appiattire un array</h3> - -<p>Il seguente esempio è qui solo per scopi didattici. Se si desidera appiattire un array usando metodi built-in, è possibile utilizzare {{jsxref("Array.prototype.flat()")}} (che dovrebbe essere parte di ES2019 e già implementato in alcuni browser).</p> - -<pre class="brush: js">/** - * Flattens ha passato un array in un array dimensionale - * - * @params {array} arr - * @returns {array} - */ -function flatten(arr) { - const result = [] - - arr.forEach((i) => { - if (Array.isArray(i)) { - result.push(...flatten(i)) - } else { - result.push(i) - } - }) - - return result -} - -// Uso -const problem = [1, 2, 3, [4, 5, [6, 7], 8, 9]] - -flatten(problem) // [1, 2, 3, 4, 5, 6, 7, 8, 9] -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>forEach()</code> è stato aggiunto allo standard ECMA-262 nella quinta edizione; in quanto tale potrebbe non essere presente in altre implementazioni dello standard. È possibile aggirare questo problema inserendo il seguente codice all'inizio degli script, consentendo l'uso di <code>forEach()</code> nelle implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo {{jsxref("Object")}} e {{jsxref("TypeError")}} hanno i loro valori originali e quel <code>callback.call()</code> valuta il valore originale di {{jsxref("Function.prototype.call()")}}.</p> - -<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.18 -// Reference: http://es5.github.io/#x15.4.4.18 -if (!Array.prototype.forEach) { - - Array.prototype.forEach = function(callback/*, thisArg*/) { - - var T, k; - - if (this == null) { - throw new TypeError('this is null or not defined'); - } - - // 1. Let O be the result of calling toObject() passing the - // |this| value as the argument. - var O = Object(this); - - // 2. Let lenValue be the result of calling the Get() internal - // method of O with the argument "length". - // 3. Let len be toUint32(lenValue). - var len = O.length >>> 0; - - // 4. If isCallable(callback) is false, throw a TypeError exception. - // See: http://es5.github.com/#x9.11 - if (typeof callback !== 'function') { - throw new TypeError(callback + ' is not a function'); - } - - // 5. If thisArg was supplied, let T be thisArg; else let - // T be undefined. - if (arguments.length > 1) { - T = arguments[1]; - } - - // 6. Let k be 0. - k = 0; - - // 7. Repeat while k < len. - while (k < len) { - - var kValue; - - // a. Let Pk be ToString(k). - // This is implicit for LHS operands of the in operator. - // b. Let kPresent be the result of calling the HasProperty - // internal method of O with argument Pk. - // This step can be combined with c. - // c. If kPresent is true, then - if (k in O) { - - // i. Let kValue be the result of calling the Get internal - // method of O with argument Pk. - kValue = O[k]; - - // ii. Call the Call internal method of callback with T as - // the this value and argument list containing kValue, k, and O. - callback.call(T, kValue, k, O); - } - // d. Increase k by 1. - k++; - } - // 8. return undefined. - }; -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.forEach")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.find()")}}</li> - <li>{{jsxref("Array.prototype.findIndex()")}}</li> - <li>{{jsxref("Array.prototype.map()")}}</li> - <li>{{jsxref("Array.prototype.filter()")}}</li> - <li>{{jsxref("Array.prototype.every()")}}</li> - <li>{{jsxref("Array.prototype.some()")}}</li> - <li>{{jsxref("Map.prototype.forEach()")}}</li> - <li>{{jsxref("Set.prototype.forEach()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/from/index.html b/files/it/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index 83baed1267..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -tags: - - Array - - ECMAScript 2015 - - JavaScript - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Array.from()</strong></code> crea una nuova istanza <code>Array</code> copiata superficialmente da un oggetto array-like o iterabile.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-from.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">Array.from(arrayLike[, mapFn[, thisArg]]) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>arrayLike</code></dt> - <dd>Un oggetto array-like o iterabile da convertire in un array.</dd> - <dt><code>mapFn</code> {{Optional_inline}}</dt> - <dd>Funzione map per chiamare su ogni elemento dell'array.</dd> - <dt><code>thisArg</code> {{Optional_inline}}</dt> - <dd>Valore da utilizzare come <code>this</code> quando <code>mapFn</code> viene eseguita.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Una nuova istanza {{jsxref("Array")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>Array.from()</code> consente di creare <code>Array</code> da:</p> - -<ul> - <li>oggetti array-like (oggetti con una proprietà <code>length</code> ed elementi indicizzati) o</li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/iterable">oggetti iterabili</a> (oggetti in cui è possibile ottenere i suoi elementi, come ad esempio {{jsxref("Map")}} e {{jsxref("Set")}}).</li> -</ul> - -<p><code>Array.from()</code> ha un parametro opzionale <code>mapFn</code>, 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, <code>Array.from(obj, mapFn, thisArg)</code> ha lo stesso risultato di <code>Array.from(obj).map(mapFn, thisArg)</code>, tranne che non crea un array intermedio. Questo è particolarmente importante per alcune sottoclassi di array, come gli <a href="/en-US/docs/Web/JavaScript/Typed_arrays">array tipizzati</a>, poiché l'array intermedio avrebbe necessariamente valori troncati per adattarsi al tipo appropriato.</p> - -<p>La proprietà <code>length</code> del metodo <code>from()</code> è 1.</p> - -<p>In ES2015, la sintassi della classe consente la sottoclassificazione di entrambe le classi predefinite e definite dall'utente; di conseguenza, i metodi statici come <code>Array.from</code> sono "ereditati" dalle sottoclassi di <code>Array</code> e creano nuove istanze della sottoclasse, non <code>Array</code>.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Array_da_una_String">Array da una <code>String</code></h3> - -<pre class="brush: js">Array.from('foo'); -// ["f", "o", "o"]</pre> - -<h3 id="Array_da_un_Set">Array da un <code>Set</code></h3> - -<pre class="brush: js">var s = new Set(['foo', window]); -Array.from(s); -// ["foo", window]</pre> - -<h3 id="Array_da_una_Map">Array da una <code>Map</code></h3> - -<pre class="brush: js">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']; -</pre> - -<h3 id="Array_di_un_oggetto_Array-like_(arguments)">Array di un oggetto Array-like (arguments)</h3> - -<pre class="brush: js">function f() { - return Array.from(arguments); -} - -f(1, 2, 3); - -// [1, 2, 3]</pre> - -<h3 id="Utilizzo_delle_funzioni_a_freccia_e_Array.from">Utilizzo delle funzioni a freccia e <code>Array.from</code></h3> - -<pre class="brush: js">// 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] -</pre> - -<h3 id="Generatore_di_sequenze_(range)">Generatore di sequenze (range)</h3> - -<pre class="brush: js">// 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"] -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>Array.from</code> è 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 <code>Array.from</code> in implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 6a edizione, assumendo che <code>Object</code> e <code>TypeError</code> abbiano i loro valori originali e che <code>callback.call</code> 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.</p> - -<pre class="brush: js">// 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; - }; - }()); -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - - - -<p>{{Compat("javascript.builtins.Array.from")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array")}}</li> - <li>{{jsxref("Array.prototype.map()")}}</li> - <li>{{jsxref("TypedArray.from()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/includes/index.html b/files/it/web/javascript/reference/global_objects/array/includes/index.html deleted file mode 100644 index 04dc817974..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/includes/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Array.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/Array/includes -translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>includes()</strong></code> determina se un array include un certo elemento, ritornando <code>true</code> o <code>false</code> a seconda del caso</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">var <var>boolean</var> = <var>array</var>.includes(<var>searchElement</var>[, <var>fromIndex</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>searchElement</code></dt> - <dd>L'elemento da cercare.</dd> - <dt><code>fromIndex</code></dt> - <dd>Opzionale. La posizione nell'array da cui partire per cercare l'elemento <code>searchElement</code>. Un valore negativo ricerca dal valore di <code>array.length + fromIndex</code> in maniera ascendente. Il valore di default è 0.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un {{jsxref("Boolean")}}.</p> - -<h2 id="Examples">Examples</h2> - -<pre class="brush: js">[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 -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<pre class="brush: js">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; - }; -} -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> - <td>{{Spec2('ES7')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Edge</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td> - <p>{{CompatChrome(47)}}</p> - </td> - <td>43</td> - <td>{{CompatNo}}</td> - <td>14279+</td> - <td>34</td> - <td>9</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Android Webview</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - <th>Chrome for Android</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td> - <p>{{CompatChrome(47)}}</p> - </td> - <td>43</td> - <td>{{CompatNo}}</td> - <td>34</td> - <td>9</td> - <td> - <p>{{CompatChrome(47)}}</p> - </td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("TypedArray.prototype.includes()")}}</li> - <li>{{jsxref("String.prototype.includes()")}}</li> - <li>{{jsxref("Array.prototype.indexOf()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/index.html b/files/it/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 844d1baf00..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,480 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -<div>{{JSRef}}</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>L'oggetto <strong><code>Array </code></strong>di JavaScript è un oggetto globale che è utilizzato nella costruzione di array; che sono oggetti di alto-livello del tipo lista.</p> - -<p><strong>Creare un Array</strong></p> - -<pre class="brush: js">var fruits = ["Apple", "Banana"]; - -console.log(fruits.length); -// 2 -</pre> - -<p><strong>Accedere (index into) ad un Array item</strong></p> - -<pre class="brush: js">var first = fruits[0]; -// Apple - -var last = fruits[fruits.length - 1]; -// Banana -</pre> - -<p><strong>Loop in un Array</strong></p> - -<pre class="brush: js">fruits.forEach(function (item, index, array) { - console.log(item, index); -}); -// Apple 0 -// Banana 1 -</pre> - -<p><strong>Aggiungere alla fine di un Array</strong></p> - -<pre class="brush: js">var newLength = fruits.push("Orange"); -// ["Apple", "Banana", "Orange"] -</pre> - -<p><strong>Rimuovere dalla fine di un Array</strong></p> - -<pre class="brush: js">var last = fruits.pop(); // remove Orange (from the end) -// ["Apple", "Banana"]; -</pre> - -<p><strong>Rimuovere dall'inizio di un Array</strong></p> - -<pre class="brush: js">var first = fruits.shift(); // remove Apple from the front -// ["Banana"]; -</pre> - -<p><strong>Aggiungere al'inizio di un Array</strong></p> - -<pre class="brush: js">var newLength = fruits.unshift("Strawberry") // add to the front -// ["Strawberry", "Banana"]; -</pre> - -<p><strong>Trovare l'indice di un elemento nell'Array</strong></p> - -<pre class="brush: js">fruits.push("Mango"); -// ["Strawberry", "Banana", "Mango"] - -var pos = fruits.indexOf("Banana"); -// 1 -</pre> - -<p><strong>Rimuovere un elemento tramite la Posizione dell'Indice</strong></p> - -<pre class="brush: js">var removedItem = fruits.splice(pos, 1); // this is how to remove an item -// ["Strawberry", "Mango"] -</pre> - -<p><strong>Copiare un Array</strong></p> - -<pre class="brush: js">var shallowCopy = fruits.slice(); // this is how to make a copy -// ["Strawberry", "Mango"] -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>[<var>element0</var>, <var>element1</var>, ..., <var>elementN</var>] -new Array(<var>element0</var>, <var>element1</var>[, ...[, <var>elementN</var>]]) -new Array(<var>arrayLength</var>)</code></pre> - -<dl> - <dt><code>element<em>N</em></code></dt> - <dd>Un array JavaScript è inizializzato con gli elementi dati, eccetto nel caso in cui un argomento singolo è passato al costruttore dell'<code>Array</code> e l'argomento è un numero. (Vedere sotto.) Notare che questo caso speciale si applica solo agli array JavaScript creati con il costruttore <code>Array</code>, non array literals creati con la sintassi a parentesi.</dd> - <dt><code>arrayLength</code></dt> - <dd>Se l'unico argomento passato al costruttore <code>Array</code> è un integer tra 0 e 2<sup>32</sup>-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.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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.</p> - -<p>Alcuni pensano che<a class="external" href="http://www.andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/"> non si dovrebbe un utilizzare un array come un associative array</a>. In ogni caso, si può utilizzare un semplice {{jsxref("Global_Objects/Object", "objects")}} invece, con i suoi avvertimenti. Vedere il post <a class="external" href="http://www.less-broken.com/blog/2010/12/lightweight-javascript-dictionaries.html">Lightweight JavaScript dictionaries with arbitrary keys</a> come esempio.</p> - -<h3 id="Accedere_ad_elementi_di_array">Accedere ad elementi di array </h3> - -<p>Gli array JavaScript sono indicizzati a zero: il primo elemento di un array è all'indice <code>0</code>, 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 <code>undefined</code>.</p> - -<pre class="brush: js">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' -</pre> - -<p>Gli elementi dell'Array sono proprietà dell'oggetto allo stesso modo che <code>toString</code> è 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:</p> - -<pre class="brush: js">console.log(arr.0); // a syntax error -</pre> - -<p>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 <code>'3d'</code>, la si potrebbe referenziare solamente utilizzando la notazione parentesi quadre. E.g.:</p> - -<pre class="brush: js">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; -console.log(years.0); // a syntax error -console.log(years[0]); // works properly -</pre> - -<pre class="brush: js">renderer.3d.setTexture(model, 'character.png'); // a syntax error -renderer['3d'].setTexture(model, 'character.png'); // works properly -</pre> - -<p>Notare che nell'esempio <code>3d</code>, <code>'3d'</code> doveva essere messo tra virgolette. E' possibile mettere tra virgolette anche gli indici dell'array JavaScript (e.g., <code>years['2']</code> invece di <code>years[2]</code>), anche se non necessario. Il 2 in <code>years[2]</code> è costretto in una stringa dal motore di JavaScript attraverso una implicita conversione <code>toString</code>. E' per questa ragione che <code>'2'</code> e <code>'02'</code> riferirebbero a due differenti slot nell'oggetto <code>years</code> ed il seguente esempio potrebbe essere <code>true</code>:</p> - -<pre class="brush: js">console.log(years['2'] != years['02']); -</pre> - -<p>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):</p> - -<pre><code>var promise = { - 'var' : 'text', - 'array': [1, 2, 3, 4] -}; - -console.log(promise['var']);</code></pre> - -<h3 id="Relzione_tra_length_e_proprietà_numeriche">Relzione tra <code>length</code> e proprietà numeriche</h3> - -<p>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.</p> - -<pre class="brush: js">var fruits = []; -fruits.push('banana', 'apple', 'peach'); - -console.log(fruits.length); // 3 -</pre> - -<p>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:</p> - -<pre class="brush: js">fruits[5] = 'mango'; -console.log(fruits[5]); // 'mango' -console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] -console.log(fruits.length); // 6 -</pre> - -<p>Aumentando{{jsxref("Array.length", "length")}}.</p> - -<pre class="brush: js">fruits.length = 10; -console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] -console.log(fruits.length); // 10 -</pre> - -<p>Diminuendo la proprietà {{jsxref("Array.length", "length")}}, comunque cancella gli elementi.</p> - -<pre class="brush: js">fruits.length = 2; -console.log(Object.keys(fruits)); // ['0', '1'] -console.log(fruits.length); // 2 -</pre> - -<p>La spiegazione è ampliata nella pagina{{jsxref("Array.length")}}.</p> - -<h3 id="Creare_un_array_utilizzando_il_risultato_di_un_match">Creare un array utilizzando il risultato di un match</h3> - -<p>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:</p> - -<pre class="brush: js">// 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'); -</pre> - -<p>Le proprietà ed elementi restituiti da questo match sono le seguenti:</p> - -<table class="fullwidth-table"> - <tbody> - <tr> - <td class="header">Property/Element</td> - <td class="header">Description</td> - <td class="header">Example</td> - </tr> - <tr> - <td><code>input</code></td> - <td>Una proprietà read-only che riflette la stinga originale verso la quale l'espressione irregolare era stata abbinata.</td> - <td>cdbBdbsbz</td> - </tr> - <tr> - <td><code>index</code></td> - <td>Una proprietà read-only su indice base-zeroindex dell'abbinamento nella stringa.</td> - <td>1</td> - </tr> - <tr> - <td><code>[0]</code></td> - <td>Un elemento read-only che specifica gli ultimi caratteri abbinati.</td> - <td>dbBd</td> - </tr> - <tr> - <td><code>[1], ...[n]</code></td> - <td>Elementi read-only che specificano gli abbinamenti di sottostringa in parentesi, se inclusi nella espressione regolare. Il numero di possibili sottostringhe in parentesi è illimitato.</td> - <td>[1]: bB<br> - [2]: d</td> - </tr> - </tbody> -</table> - -<h2 id="Proprietà">Proprietà</h2> - -<dl> - <dt><code>Array.length</code></dt> - <dd>Il costruttore della proprietà lunghezza <code>Array</code> il cui valore è 1.</dd> - <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> - <dd>La funzione del costruttore che è usata per creare oggetti derivati.</dd> - <dt>{{jsxref("Array.prototype")}}</dt> - <dd>Permette l'addizione di proprietà a tutti gli oggetti array.</dd> -</dl> - -<h2 id="Metodi">Metodi</h2> - -<dl> - <dt>{{jsxref("Array.from()")}} {{experimental_inline}}</dt> - <dd>Crea una nuova istanza <code>Array</code> da un oggetto del tipo array o iterabile.</dd> - <dt>{{jsxref("Array.isArray()")}}</dt> - <dd>Restituisce true se una variabile è un array, altrimenti false.</dd> - <dt>{{jsxref("Array.observe()")}} {{experimental_inline}}</dt> - <dd>In modo asincrono osserva i cambiamenti agli Arrays, come{{jsxref("Object.observe()")}} per gli oggetti. Provvede un flusso di cambiamenti in ordine di occorrenza.</dd> - <dt>{{jsxref("Array.of()")}} {{experimental_inline}}</dt> - <dd>Crea una nuova istanza <code>Array</code> con un variabile numero di argomenti, nonostante il numero o i tipi di argomenti.</dd> -</dl> - -<h2 id="Istanze_di_Array">Istanze di<code> Array</code> </h2> - -<p>Tutte le istanze di <code>Array</code> ereditano da {{jsxref("Array.prototype")}}. L'oggetto prototype del costruttore <code>Array</code> può essere modificato per influenzare tutte le istanze di <code>Array</code>.</p> - -<h3 id="Proprietà_2">Proprietà</h3> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> - -<h3 id="Metodi_2">Metodi</h3> - -<h4 id="Metodi_mutatori">Metodi mutatori</h4> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> - -<h4 id="Metodi_per_accedere">Metodi per accedere</h4> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> - -<h4 id="Metodi_di_iterazione">Metodi di iterazione</h4> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}} </div> - -<h2 id="Metodi_generici_Array"><code><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="background-color: #ffffff;">Metodi generici </span></font>Array</code> </h2> - -<div class="warning"> -<p><strong>Array generics are non-standard, deprecated and will get removed near future</strong>. Note that you can not rely on them cross-browser. However, there is a <a href="https://github.com/plusdude/array-generics">shim available on GitHub</a>.</p> -</div> - -<p>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 <var>str</var> sia una lettera, si scriverebbe:</p> - -<pre class="brush: js">function isLetter(character) { - return character >= 'a' && character <= 'z'; -} - -if (Array.prototype.every.call(str, isLetter)) { - console.log("The string '" + str + "' contains only letters!"); -} -</pre> - -<p>Tale notazione è dispersiva e JavaScript 1.6 ha introdotto un generico shorthand:</p> - -<pre class="brush: js">if (Array.every(str, isLetter)) { - console.log("The string '" + str + "' contains only letters!"); -} -</pre> - -<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("Global_Objects/String", "String")}}.</p> - -<p>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:</p> - -<pre class="brush: js">// 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]); - } -}()); -</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Creare_un_array">Creare un array</h3> - -<p>Il seguente esempio crea un array, <code>msgArray</code>, con una lunghezza di 0, poi assegna valori a <code>msgArray[0]</code> e <code>msgArray[99]</code>, cambiando la lunghezza dell'array a 100.</p> - -<pre class="brush: js">var msgArray = []; -msgArray[0] = 'Hello'; -msgArray[99] = 'world'; - -if (msgArray.length === 100) { - console.log('The length is 100.'); -} -</pre> - -<h3 id="Creare_un_array_bidimensionale">Creare un array bidimensionale</h3> - -<p>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.</p> - -<pre class="brush: js">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')); -</pre> - -<p>Ecco l'output:</p> - -<pre class="eval">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 -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4', 'Array')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>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")}}</td> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array-objects', 'Array')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>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")}}</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser </h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedere_anche">Vedere anche:</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> - <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> - <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/indexof/index.html b/files/it/web/javascript/reference/global_objects/array/indexof/index.html deleted file mode 100644 index 658957c67d..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/indexof/index.html +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Array.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf -tags: - - Array - - JavaScript - - Prototype - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>indexOf()</strong></code> restituisce il primo indice in cui è possibile trovare un determinato elemento nell'array o -1 se non è presente.</p> - -<div class="note"> -<p><strong>Note:</strong> Per il metodo String, consultare {{jsxref("String.prototype.indexOf()")}}.</p> -</div> - -<div>{{EmbedInteractiveExample("pages/js/array-indexof.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.indexOf(<var>searchElement[</var>, <var>fromIndex]</var>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>searchElement</code></dt> - <dd>Elemento da localizzare nell'array.</dd> - <dt><code>fromIndex</code> {{optional_inline}}</dt> - <dd>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).</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Il primo indice dell'elemento nell'array; <strong>-1</strong> se non trovato.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>indexOf()</code> compara <code>searchElement</code> con gli elementi dell'array usando <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_equality_operators">strict equality</a> (lo stesso metodo utilizzato dall'operatore <code>===</code> o triple-equals).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_indexOf()">Usare <code>indexOf()</code></h3> - -<p>Nell'esempio seguente viene utilizzato <code>indexOf()</code> per individuare i valori in un array.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="Trovare_tutte_le_occorrenze_di_un_elemento">Trovare tutte le occorrenze di un elemento</h3> - -<pre class="brush: js">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] -</pre> - -<h3 id="Trovare_se_un_elemento_esiste_nell'array_o_meno_ed_aggiornare_l'array">Trovare se un elemento esiste nell'array o meno ed aggiornare l'array</h3> - -<pre class="brush: js">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. -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>indexOf()</code> è 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 <code>indexOf()</code> 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.</p> - -<pre class="brush: js">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); -</pre> - -<p>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.</p> - -<pre class="brush: js">// 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; - }; -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.indexOf")}}</p> -</div> - -<h2 id="Note_di_compatibilità">Note di compatibilità</h2> - -<ul> - <li>A partire da Firefox 47 {{geckoRelease(47)}}, questo metodo non restituirà più <code>-0</code>. Ad esempio, <code>[0].indexOf(0, -0)</code> restituirà sempre <code>+0</code> ({{bug(1242043)}}).</li> -</ul> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> - <li>{{jsxref("TypedArray.prototype.indexOf()")}}</li> - <li>{{jsxref("String.prototype.indexOf()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/isarray/index.html b/files/it/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index d7aaf864bf..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Array - - ECMAScript 5 - - JavaScript - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Array.isArray()</strong></code> determina se il valore passato è un {{jsxref("Array")}}.</p> - -<pre class="brush: js">Array.isArray([1, 2, 3]); // true -Array.isArray({foo: 123}); // false -Array.isArray('foobar'); // false -Array.isArray(undefined); // false -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">Array.isArray(<var>value</var>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>value</code></dt> - <dd>Il valore da verificare.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p><code>true</code> se il valore è un {{jsxref("Array")}}; altrimenti, <code>false</code>.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Se il valore è un {{jsxref("Array")}}, viene ritornato <code>true</code>; altrimenti viene ritornato <code>false</code>.</p> - -<p>Vedi l'articolo <a href="http://web.mit.edu/jwalden/www/isArray.html">“Determining with absolute accuracy whether or not a JavaScript object is an array”</a> per maggiori dettagli. Data un'istanza {{jsxref("TypedArray")}}, viene ritornato sempre <code>false</code>.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">// 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 }); -</pre> - -<h3 id="instanceof_vs_isArray"><code>instanceof</code> vs <code>isArray</code></h3> - -<p>Quando si verifica l'istanza <code>Array</code>, <code>Array.isArray</code> è preferito su <code>instanceof</code> perché funziona attraverso gli <code>iframes</code>.</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>L'esecuzione del seguente codice prima di qualsiasi altro codice creerà <code>Array.isArray()</code> se non è nativamente disponibile.</p> - -<pre class="brush: js">if (!Array.isArray) { - Array.isArray = function(arg) { - return Object.prototype.toString.call(arg) === '[object Array]'; - }; -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.8.5.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.isArray")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/join/index.html b/files/it/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 8483c817ac..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - Array - - JavaScript - - Prototype - - Referenza - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>join()</strong></code> unisce tutti gli elementi di un array (o di un <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array di </a>oggetti) in una stringa che viene restituita.</p> - -<pre class="brush: js">var a = ['Wind', 'Rain', 'Fire']; -a.join(); // 'Wind,Rain,Fire' -a.join('-'); // 'Wind-Rain-Fire'</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.join() -<var>arr</var>.join(<var>separatore</var>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>separatore</code> {{optional_inline}}</dt> - <dd>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 <code>separatore</code> è una stringa vuota, tutti gli elementi sono uniti senza alcun carattere intemedio.</dd> -</dl> - -<h3 id="Valore_di_risposta">Valore di risposta</h3> - -<p>Una stringa con tutti con tutti gli elementi dell'array uniti. Se <code><em>arr</em>.length</code> è <code>0</code>, viene restituita una stringa vuota.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Le stringe ottenute dalla conversione di tutti gli elementi dell'array sono unite in un unica stringa.</p> - -<div class="warning"> -<p>Se un elemento è <code>undefined</code> o <code>null</code>, sarà convertito in una stringa vuota.</p> -</div> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Quattro_modi_per_concatenare_un_array">Quattro modi per concatenare un array</h3> - -<p>Il seguente esempio crea un array, <code>a</code>, 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.</p> - -<pre class="brush: js">var a = ['Wind', 'Rain', 'Fire']; -a.join(); // 'Wind,Rain,Fire' -a.join(', '); // 'Wind, Rain, Fire' -a.join(' + '); // 'Wind + Rain + Fire' -a.join(''); // 'WindRainFire'</pre> - -<h3 id="Unione_di_un_oggetto_di_tipo_array">Unione di un oggetto di tipo array</h3> - -<p>Il seguente esempio unisce un oggetto di tipo array (<code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>), chiamando {{jsxref("Function.prototype.call")}} con <code>Array.prototype.join</code>.</p> - -<pre class="brush: js">function f(a, b, c) { - var s = Array.prototype.join.call(arguments); - console.log(s); // '<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">1,a,true'</span></span></span></span> -} -f(1, 'a', true);</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.1.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.join")}}</p> -</div> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li>{{jsxref("String.prototype.split()")}}</li> - <li>{{jsxref("Array.prototype.toString()")}}</li> - <li>{{jsxref("TypedArray.prototype.join()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/keys/index.html b/files/it/web/javascript/reference/global_objects/array/keys/index.html deleted file mode 100644 index 78212d221f..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/keys/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: Array.prototype.keys() -slug: Web/JavaScript/Reference/Global_Objects/Array/keys -translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>keys()</strong></code> ritorna un nuovo oggetto <code><strong>Array Iterator</strong></code> contenente le chiavi di ogni indice dell'array.</p> - -<pre class="brush: js">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 } -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.keys()</pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un nuovo oggetto {{jsxref("Array")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="I_Key_iterator_non_ignorano_gli_elementi_vuoti">I Key iterator non ignorano gli elementi vuoti</h3> - -<pre class="brush: js">var arr = ['a', , 'c']; -var sparseKeys = Object.keys(arr); -var denseKeys = [...arr.keys()]; -console.log(sparseKeys); // ['0', '2'] -console.log(denseKeys); // [0, 1, 2] -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.prototype.keys', 'Array.prototype.keys')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.keys")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.values()")}}</li> - <li>{{jsxref("Array.prototype.entries()")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html deleted file mode 100644 index c4170455f6..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: Array.prototype.lastIndexOf() -slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf -tags: - - Array - - ECMAScript 5 - - JavaScript - - Protototipo - - Prototype - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>lastIndexOf()</strong></code> 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 <code>fromIndex</code>.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}</div> - -<p class="hidden">Il codice sorgere per questo esempio interattivo è conservato all' interno di una repository di GitHub. Se vuoi contribuire all progetto di esempi interattivi, perfavore clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviaci una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.lastIndexOf(<var>searchElement</var>) -<var>arr</var>.lastIndexOf(<var>searchElement</var>, <var>fromIndex</var>) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>searchElement</code></dt> - <dd>Elemento da trovare nell' array.</dd> - <dt><code>fromIndex</code> {{optional_inline}}</dt> - <dd>L'indice da cui iniziare a cercare al contrario. Di defaults la lunghezza dell' array meno uno (<code>arr.length - 1</code>), 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.</dd> -</dl> - -<h3 id="Valori_restituiti">Valori restituiti</h3> - -<p>L'ultimo indice dell' elemento nell' array; <strong>-1</strong> se non trovato.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>lastIndexOf</code> compara <code>searchElement</code> a gli elementi dell' array usando <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">strict equality</a> (lo stesso metodo usato ===, o triple-equals, operator).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzo_di_lastIndexOf">Utilizzo di <code>lastIndexOf</code></h3> - -<p>L'esempio seguente usa <code>lastIndexOf</code> per trovare i valori in un array.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="Trovare_tutte_le_posizioni_di_un_elemento">Trovare tutte le posizioni di un elemento</h3> - -<p>Il seguente esempio usa <code>lastIndexOf</code> per trovare tutti gli elementi nell' array, usando {{jsxref("Array.prototype.push", "push")}} per essere aggiunti in un array come vengono trovati.</p> - -<pre class="brush: js">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] -</pre> - -<p>Nota che non abbiamo considerato <code>idx == 0</code>perchè l'elemento sarà sempre troavto indipendemente da <code>il parametro fromIndex</code> se è il primo elemento dell'array. TQuesto è diveso dal metodo {{jsxref("Array.prototype.indexOf", "indexOf")}}.</p> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>lastIndexOf</code> è 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 <code>lastIndexOf</code> 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.</p> - -<pre class="brush: js">// 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; - }; -} -</pre> - -<p>Ancora, nota che questa implementazione mira alla compatibilità assoluta con <code>lastIndexOf</code> in Firefox e SpiderMonkey JavaScript engine, includendo alcuni casi che sono considerati estremi. ISe hai intenzione di usare questo in applicazioni reali, potresti calcolare <code>from</code> con un codice meno complicato se ignori questi casi.</p> - -<h2 id="Descrizione_2">Descrizione</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Descrizione</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_il_browser">Compatibilità con il browser</h2> - -<div> -<div class="hidden">La tabella della compatibilità in questa pagina è stata generata da strutture dati. Se vorresti contribuire ai dati, perfavore da un' occhiata a <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una pull request.</div> - -<p>{{Compat("javascript.builtins.Array.lastIndexOf")}}</p> -</div> - -<h2 id="Note_di_compatibilità">Note di compatibilità</h2> - -<ul> - <li>Partendo da Firefox 47 {{geckoRelease(47)}}, <code>questo metodo non restituirà più -0</code>. Per esempio, <code>[0].lastIndexOf(0, -0)</code> Ora restituirà sempre <code>+0</code> ({{bug(1242043)}}).</li> -</ul> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.indexOf()")}}</li> - <li>{{jsxref("TypedArray.prototype.lastIndexOf()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/length/index.html b/files/it/web/javascript/reference/global_objects/array/length/index.html deleted file mode 100644 index a36a6b5204..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/length/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.length -slug: Web/JavaScript/Reference/Global_Objects/Array/length -translation_of: Web/JavaScript/Reference/Global_Objects/Array/length ---- -<div>{{JSRef}}</div> - -<div>La proprieta' <strong>length</strong> setta o restituisce il numero di elementi in un array. E' un intero a 32 bit, sempre maggiore del piu' grande indice dell'array.</div> - -<div> </div> - -<pre class="brush: js">var items = ['shoes', 'shirts', 'socks', 'sweaters']; -items.length; - -// returns 4</pre> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Puoi impostare la proprietà <strong>length</strong> di un array per troncare o estendere l'array stesso.</p> - -<pre class="brush: js">var a = [1,2,3]; -a.length=2; -// a is now [1, 2] - -a.length = 10 -// a is now [1, 2, undefined × 8] -</pre> - -<h3 id="sect1"> </h3> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Iterare_su_un_array">Iterare su un array</h3> - -<p>Nel seguente esempio, l'array <em>numbers</em> viene iterarato e ciascun elemento viene moltiplicato per 2.</p> - -<pre class="brush: js">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] -</pre> - -<h3 id="Specifiche">Specifiche</h3> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità">Compatibilità</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="sect2"> </h2> diff --git a/files/it/web/javascript/reference/global_objects/array/map/index.html b/files/it/web/javascript/reference/global_objects/array/map/index.html deleted file mode 100644 index 808b4fc728..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/map/index.html +++ /dev/null @@ -1,323 +0,0 @@ ---- -title: Array.prototype.map() -slug: Web/JavaScript/Reference/Global_Objects/Array/map -tags: - - Array - - ECMAScript 5 - - JavaScript - - Prototype - - Referenza - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/map ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>map()</strong></code> crea un nuovo array con i risultati della chiamata di una funzione fornita su ogni elemento dell'array chiamante.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> - -<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request." </p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>var new_array = arr</var>.map(function <var>callback(currentValue[, index[, array]]) { - </var>// Ritorna un elemento per new_array<var> -}</var>[, <var>thisArg</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione che produce un elemento del nuovo array, prendendo tre argomenti: - <dl> - <dt> </dt> - <dt><code>currentValue</code></dt> - <dd>L'elemento corrente in elaborazione nell'array.</dd> - <dt><code>index</code>{{optional_inline}}</dt> - <dd>L'indice dell'elemento corrente in elaborazione nell'array.</dd> - <dt><code>array</code>{{optional_inline}}</dt> - <dd>L'array a cui viene applicato <code>map</code>.</dd> - </dl> - </dd> - <dt><code>thisArg</code>{{optional_inline}}</dt> - <dd>Valore da utilizzare come <code>this</code> quando viene eseguito <code>callback</code>.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un nuovo array con ciascun elemento che è il risultato della funzione di callback.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>map</code> chiama il <code>callback</code> fornito <strong>una volta per ciascun elemento</strong> in un array, in ordine, e costruisce un nuovo array dai risultati. <code>callback</code> viene invocato solo per gli indici dell'array che hanno valori assegnati, incluso <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a>. Non viene chiamato per gli elementi mancanti dell'array (ovvero, gli indici che non sono mai stati impostati, che sono stati cancellati o a cui non è mai stato assegnato un valore).</p> - -<p>Poichè <code>map</code> costruisce un nuovo array, usarlo quando non si utilizza l'array restituito è un anti-pattern; usa <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach"><code>forEach</code></a> o <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for-of</a></code> invece. Segni che non dovresti usare map: A) Non stai usando l'array restituito, e/o B) Non stai restituendo un valore dal callback.</p> - -<p><code>callback</code> viene invocato con tre argomenti: il valore dell'elemento, l'indice dell'elemento e l'oggetto Array che viene iterato.</p> - -<p>Se viene fornito il parametro <code>thisArg</code> a <code>map</code>, verrà utilizzato come valore <code>this</code> del callback. Altrimenti, il valore {{jsxref("undefined")}} sarà usato come valore <code>this</code>. Il valore <code>this</code> alla fine osservabile da <code>callback</code> è determinato secondo <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">le consuete regole per determinare il <code>this</code> visto da una funzione</a>.</p> - -<p><code>map</code> non muta l'array su cui è chiamato (sebbene <code>callback</code>, se invocato, possa farlo).</p> - -<p>L'intervallo di elementi elaborati da <code>map</code> viene impostato prima della prima chiamata del <code>callback</code>. Gli elementi aggiunti all'array dopo che la chiamata a <code>map</code> inizia non saranno calcolati da <code>callback</code>. Se i valori degli elementi esistenti dell'array vengono modificati, il valore passato a <code>callback</code> sarà il valore al momento in cui <code>map</code> li visita. Gli elementi che vengono cancellati dopo che la chiamata a <code>map</code> inizia e prima di essere visitati non vengono visitati.</p> - -<p>A causa dell'algoritmo definito nella specifica, se l'array su cui è stata chiamato <code>map</code> è sparso, l'array risultante sarà sparso, mantenendo vuoti gli stessi indici.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Mappare_una_serie_di_numeri_ad_un_array_di_radici_quadrate">Mappare una serie di numeri ad un array di radici quadrate</h3> - -<p>Il seguente codice accetta un array di numeri e crea un nuovo array contenente le radici quadrate dei numeri nel primo array.</p> - -<pre class="brush: js">var numbers = [1, 4, 9]; -var roots = numbers.map(function(num) { -return Math.sqrt(num) -}); -// roots è ora [1, 2, 3] -// numbers è ancora [1, 4, 9] -</pre> - -<h3 id="Usare_map_per_riformattare_gli_oggetti_in_un_array">Usare <code>map</code> per riformattare gli oggetti in un array</h3> - -<p>Il seguente codice accetta un array di oggetti e crea un nuovo array contenente gli oggetti appena riformattati.</p> - -<pre class="brush: js">var kvArray = [{key: 1, value: 10}, - {key: 2, value: 20}, - {key: 3, value: 30}]; - -var reformattedArray = kvArray.map(obj =>{ - var rObj = {}; - rObj[obj.key] = obj.value; - return rObj; -}); -// reformattedArray è ora [{1: 10}, {2: 20}, {3: 30}], - -// kvArray è ancora: -// [{key: 1, value: 10}, -// {key: 2, value: 20}, -// {key: 3, value: 30}] -</pre> - -<h3 id="Mappare_un_array_di_numeri_usando_una_funzione_che_contiene_un_argomento">Mappare un array di numeri usando una funzione che contiene un argomento</h3> - -<p>Il codice seguente mostra come funziona <code>map</code> quando viene utilizzata una funzione che richiede un argomento. L'argomento verrà assegnato automaticamente da ciascun elemento dell'array mentre <code>map</code> itera l'array originale.</p> - -<pre class="brush: js">var numbers = [1, 4, 9]; -var doubles = numbers.map(function(num) { - return num * 2; -}); - -// doubles is now [2, 8, 18] -// numbers is still [1, 4, 9] -</pre> - -<h3 id="Usare_map_genericamente">Usare <code>map</code> genericamente</h3> - -<p>Questo esempio mostra come usare map su una {{jsxref("String")}} per ottenere un array di byte nella codifica ASCII che rappresenta i valori dei caratteri:</p> - -<pre class="brush: js">var a = Array.prototype.map.call('Hello World', function(x) { - return x.charCodeAt(0); -}); -// a ora equivale a [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] -</pre> - -<h3 id="Usare_map_con_querySelectorAll">Usare <code>map</code> con <code>querySelectorAll</code></h3> - -<p>Questo esempio mostra come iterare attraverso una raccolta di oggetti raccolti da <code>querySelectorAll</code>. Questo perchè <code>querySelectorAll</code> restituisce una <em><strong>NodeList</strong></em> che è una raccolta di oggetti.<br> - In questo caso restituiamo sullo schermo tutti i valori delle opzioni selezionate:</p> - -<pre class="brush: js">var elems = document.querySelectorAll('select option:checked'); -var values = Array.prototype.map.call(elems, function(obj) { - return obj.value; -}); -</pre> - -<p>Il modo più semplice sarebbe utilizzare il metodo {{jsxref("Array.from()")}}.</p> - -<h3 id="Caso_d'uso_ingannevole">Caso d'uso ingannevole</h3> - -<p><a href="http://www.wirfs-brock.com/allen/posts/166">(inspired by this blog post)</a></p> - -<p>È normale utilizzare il callback con un argomento (l'elemento che viene attraversato). Alcune funzioni sono anche comunemente utilizzate con un argomento, anche se accettano argomenti opzionali aggiuntivi. Queste abitudini possono portare a comportamenti confusi.</p> - -<pre class="brush: js" dir="rtl">// Consider: -['1', '2', '3'].map(parseInt); -// Mentre ci si potrebbe aspettare [1, 2, 3] -// Il risultato effettivo è [1, NaN, NaN] - -// parseInt è spesso usato con un argomento, ma ne prende due. -// Il primo è un'espressione e il secondo è la radice. -// Alla funzione di callback, Array.prototype.map passa 3 argomenti: -// l'elemento, l'indice e l'array -// Il terzo argomento è ignorato da parseInt, ma non il secondo, -// da qui l'eventuale confusione. Vedi il post del blog per maggiori dettagli -// Se il link non funziona -// ecco un esempio conciso dei passaggi di iterazione: -// parseInt(string, radix) -> map(parseInt(value, index)) -// first iteration (index is 0): parseInt('1', 0) // results in parseInt('1', 0) -> 1 -// second iteration (index is 1): parseInt('2', 1) // results in parseInt('2', 1) -> NaN -// third iteration (index is 2): parseInt('3', 2) // results in parseInt('3', 2) -> NaN - -function returnInt(element) { - return parseInt(element, 10); -} - -['1', '2', '3'].map(returnInt); // [1, 2, 3] -// Il risultato effettivo è un array di numeri (come previsto) - -// Come sopra, ma usando la sintassi della funzione a freccia concisa -['1', '2', '3'].map( str => parseInt(str) ); - -// Un modo più semplice per ottenere quanto sopra, evitando il "gotcha": -['1', '2', '3'].map(Number); // [1, 2, 3] -// ma a differenza di `parseInt` restituirà anche una notazione esponenziale mobile o (risolta): -['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300] -</pre> - -<p>Un output alternativo del metodo map che viene chiamato con parseInt come parametro viene eseguito come segue:</p> - -<pre class="brush: js">var xs = ['10', '10', '10']; - -xs = xs.map(parseInt); - -console.log(xs); -// Il risultato effettivo di 10,NaN,2 potrebbe essere inaspettato in base alla descrizione precedente.</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>map</code> è stato aggiunto allo standard ECMA-262 nella 5a edizione; in quanto tale potrebbe non essere presente in tutte le implementazioni dello standard. Puoi aggirare questo problema inserendo il seguente codice all'inizio degli script, consentendo l'uso di <code>map</code> in implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo {{jsxref("Object")}}, {{jsxref("TypeError")}}, e {{jsxref("Array")}} hanno i loro valori originali e che <code>callback.call</code> restituisce il valore originale di <code>{{jsxref("Function.prototype.call")}}</code>.</p> - -<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.19 -// Reference: http://es5.github.io/#x15.4.4.19 -if (!Array.prototype.map) { - - Array.prototype.map = function(callback/*, thisArg*/) { - - var T, A, k; - - if (this == null) { - throw new TypeError('this is null or not defined'); - } - - // 1. Let O be the result of calling ToObject passing the |this| - // value as the argument. - var O = Object(this); - - // 2. Let lenValue be the result of calling the Get internal - // method of O with the argument "length". - // 3. Let len be ToUint32(lenValue). - var len = O.length >>> 0; - - // 4. If IsCallable(callback) is false, throw a TypeError exception. - // See: http://es5.github.com/#x9.11 - if (typeof callback !== 'function') { - throw new TypeError(callback + ' is not a function'); - } - - // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. - if (arguments.length > 1) { - T = arguments[1]; - } - - // 6. Let A be a new array created as if by the expression new Array(len) - // where Array is the standard built-in constructor with that name and - // len is the value of len. - A = new Array(len); - - // 7. Let k be 0 - k = 0; - - // 8. Repeat, while k < len - while (k < len) { - - var kValue, mappedValue; - - // a. Let Pk be ToString(k). - // This is implicit for LHS operands of the in operator - // b. Let kPresent be the result of calling the HasProperty internal - // method of O with argument Pk. - // This step can be combined with c - // c. If kPresent is true, then - if (k in O) { - - // i. Let kValue be the result of calling the Get internal - // method of O with argument Pk. - kValue = O[k]; - - // ii. Let mappedValue be the result of calling the Call internal - // method of callback with T as the this value and argument - // list containing kValue, k, and O. - mappedValue = callback.call(T, kValue, k, O); - - // iii. Call the DefineOwnProperty internal method of A with arguments - // Pk, Property Descriptor - // { Value: mappedValue, - // Writable: true, - // Enumerable: true, - // Configurable: true }, - // and false. - - // In browsers that support Object.defineProperty, use the following: - // Object.defineProperty(A, k, { - // value: mappedValue, - // writable: true, - // enumerable: true, - // configurable: true - // }); - - // For best browser support, use the following: - A[k] = mappedValue; - } - // d. Increase k by 1. - k++; - } - - // 9. return A - return A; - }; -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.map")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>L'oggetto {{jsxref("Map")}}</li> - <li>{{jsxref("Array.from()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/of/index.html b/files/it/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 808c1dda2c..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Array.of()</strong></code> crea una nuova istanza di <code>Array</code> accettando un numero variabile di argomenti, indipendentemente dal numero o dal tipo degli argomenti.</p> - -<p>La differenza tra <code><strong>Array.of()</strong></code> ed il costruttore <code><strong>Array</strong></code> è nella gestione degli argomenti di tipo intero: <code><strong>Array.of(7)</strong></code> crea un array con un singolo elemento, <code>7</code>, mentre <code><strong>Array(7)</strong></code> crea un array vuoto con la proprietà <code>length</code> settata a 7 (<strong>Nota:</strong> questo implica un array di <code>7</code> elementi vuoti, non elementi col valore <code>undefined</code> assegnato).</p> - -<pre class="brush: js">Array.of(7); // [7] -Array.of(1, 2, 3); // [1, 2, 3] - -Array(7); // [ , , , , , , ] -Array(1, 2, 3); // [1, 2, 3] -</pre> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">Array.of(<var>element0</var>[, <var>element1</var>[, ...[, <var>elementN</var>]]])</pre> - -<h3 id="Parameteri">Parameteri</h3> - -<dl> - <dt><code>element<em>N</em></code></dt> - <dd>Gli elementi da assegnare all'array.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Una nuova istanz di {{jsxref("Array")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Questa funzione fa parte dello standard ECMAScript 2015. Per maggiori informazioni vedi le proposal <a href="https://gist.github.com/rwaldron/1074126"><code>Array.of</code> e <code>Array.from</code> </a> e il polyfill <a href="https://gist.github.com/rwaldron/3186576"><code>Array.of</code></a>.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">Array.of(1); // [1] -Array.of(1, 2, 3); // [1, 2, 3] -Array.of(undefined); // [undefined] -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>Eseguendo il codice seguente prima di qualsiasi altro codice verrà creato il metodo <code>Array.of()</code> se non era precedentemente esistente.</p> - -<pre class="brush: js">if (!Array.of) { - Array.of = function() { - return Array.prototype.slice.call(arguments); - }; -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.of")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array")}}</li> - <li>{{jsxref("Array.from()")}}</li> - <li>{{jsxref("TypedArray.of()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/pop/index.html b/files/it/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index 6feabb5f14..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - Array - - JavaScript - - Prototype - - Referenza - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>pop()</strong></code> rimuove <strong>l'ultimo</strong> elemento da un array e restituisce quell'elemento. Questo metodo modifica la lunghezza dell'array.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.pop()</pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'elemento rimosso dall'array; {{jsxref("undefined")}} se l'array è vuoto.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>pop</code> rimuove l'ultimo elemento da un array e restituisce quel valore al chiamante.</p> - -<p><code>pop</code> è 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à <code>length</code> che riflette l'ultimo di una serie di proprietà numeriche consecutive basate su zero potrebbero non comportarsi in alcun modo significativo.</p> - -<p>Se chiami <code>pop()</code> su un array vuoto, ritorna {{jsxref("undefined")}}.</p> - -<p>{{jsxref("Array.prototype.shift()")}} ha un comportamento simile a <code>pop</code>, ma applicato al primo elemento di un array.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Rimozione_dell'ultimo_elemento_di_un_array">Rimozione dell'ultimo elemento di un array</h3> - -<p>Il seguente codice crea l'array <code>myFish</code> contenente quattro elementi, dopo rimuove il suo ultimo elemento.</p> - -<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; - -var popped = myFish.pop(); - -console.log(myFish); // ['angel', 'clown', 'mandarin' ] - -console.log(popped); // 'sturgeon'</pre> - - - -<h3 id="Usare_apply(_)_o_call_(_)_sugli_array-like_objects">Usare apply( ) o call ( ) sugli array-like objects</h3> - -<p>Il codice seguente crea l'array-like object <code>myFish</code> contenente quattro elementi e un parametro length, poi rimuove il suo ultimo elemento e decrementa il parametro length.</p> - -<pre class="brush: js">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' -</pre> - - - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.2.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.pop")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.push()")}}</li> - <li>{{jsxref("Array.prototype.shift()")}}</li> - <li>{{jsxref("Array.prototype.unshift()")}}</li> - <li>{{jsxref("Array.prototype.concat()")}}</li> - <li>{{jsxref("Array.prototype.splice()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/push/index.html b/files/it/web/javascript/reference/global_objects/array/push/index.html deleted file mode 100644 index ad34c3da2d..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/push/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Array.prototype.push() -slug: Web/JavaScript/Reference/Global_Objects/Array/push -translation_of: Web/JavaScript/Reference/Global_Objects/Array/push ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>push()</strong></code> aggiunge uno o più elementi alla fine di un array e ne restituisce la nuova lunghezza.</p> - -<pre class="brush: js notranslate">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] -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox notranslate"><var>arr</var>.push([<var>elemento1</var>[, ...[, <var>elementoN</var>]]])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>elemento<em>N</em></code></dt> - <dd>Gli elementi da aggiungere alla fine dell'array.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>La nuova proprietà {{jsxref("Array.length", "length")}} dell'oggetto su cui è stato richiamato il metodo.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>push</code> aggiunge valori all'array.</p> - -<p><code>push</code> è 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 metodo<code>push</code> si basa sulla proprietà <code>length</code> per determinare da dove iniziare l'inserimento dei valori indicati. Se la proprietà <code>length</code> non può essere convertita in un numero, l'indice utilizzato è 0. Ciò include la possibilità che <code>length</code> sia inesistente, in tale caso <code>length</code> verrà creata.</p> - -<p>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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Aggiungere_elementi_a_un_array">Aggiungere elementi a un array</h3> - -<p>Il seguente codice crea l'array <code>sports</code> che contiene due elementi, poi aggiunge ulteriori due elementi allo stesso. La variabile <code>total</code> contiene la nuova lunghezza dell'array.</p> - -<pre class="brush: js notranslate">var sports = ['calcio', 'baseball']; -var total = sports.push('football americano', 'nuoto'); - -console.log(sports); // ['calcio', 'baseball', 'football americano', 'nuoto'] -console.log(total); // 4 -</pre> - -<h3 id="Unire_due_arrays">Unire due arrays</h3> - -<p>Questo esempio utilizza {{jsxref("Function.apply", "apply()")}} per aggiungere tutti gli elementi da un secondo array.</p> - -<p><em>Non</em> utilizzare questo metodo se il secondo array (<code>moreVegs</code> 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.</p> - -<pre class="brush: js notranslate">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'] -</pre> - -<h3 id="Utilizzo_di_un_oggetto_come_un_array">Utilizzo di un oggetto come un array</h3> - -<p>Come accennato in precedenza, <code>push</code> è intenzionalmente generica e possiamo usarla a nostro vantaggio. <code>Array.prototype.push</code> 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 <code>call</code> su <code>Array.prototype.push</code> 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.</p> - -<pre class="brush: js notranslate">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 -</pre> - -<p>Si noti che anche se <code>obj</code> non è un array, il metodo <code>push</code> ha incrementato la proprietà di <code>length</code> di<code>obj</code> come se si trattasse di un array vero e proprio.</p> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazione</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.2.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_di_Browser">Compatibilità di Browser</h2> - -<div> -<div class="hidden">La tabella di compatibilità di questa pagina viene generata da dati strutturati. Se desideri contribuire ai dati, controlla <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e invia una pull request.</div> - -<p>{{Compat("javascript.builtins.Array.push")}}</p> -</div> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.pop()")}}</li> - <li>{{jsxref("Array.prototype.shift()")}}</li> - <li>{{jsxref("Array.prototype.unshift()")}}</li> - <li>{{jsxref("Array.prototype.concat()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/reduce/index.html b/files/it/web/javascript/reference/global_objects/array/reduce/index.html deleted file mode 100644 index de063df929..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/reduce/index.html +++ /dev/null @@ -1,576 +0,0 @@ ---- -title: Array.prototype.reduce() -slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce -tags: - - Array - - Array method - - ECMAScript 5 - - JavaScript - - Method - - Prototype - - Reduce - - Referenza -translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>reduce()</strong></code> esegue una funzione <strong>reducer</strong> (che tu fornisci) su ogni elemento dell'array, risultante in un unico output.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> - -<div>I sorgenti per questo esempio interattivo è disponibile su un repository GitHub. Se desideri contribuire al progetto, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviaci una pull request.</div> - -<p>La funzione <strong>reducer</strong> accetta quattro argomenti:</p> - -<ol> - <li>Accumulatore (acc)</li> - <li>Valore corrente (cur)</li> - <li>Indice corrente (idx)</li> - <li>Array sul quale viene eseguito il metodo (src)</li> -</ol> - -<p>Il valore restituito della funzione <strong>reducer</strong> viene assegnato all'accumulatore, il cui valore viene memorizzato attraverso ogni iterazione nell'intero array e in definitiva, diventa il valore finale finale singolo.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox notranslate"><var>arr.reduce(callback(accumulator, currentValue[, index[, array]]) [, initialValue])</var></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Una funzione da eseguire su ogni elemento dell'array (tranne il primo, se non viene fornita <code>initialValue</code>), accetta 4 argomenti: - <dl> - <dt><code>accumulator</code></dt> - <dd>L'accumulatore accumula i valori di ritorno del callback. È il valore accumulato precedentemente restituito nell'ultima chiamata del callback o <code>initialValue</code>, se fornito (vedere di seguito).</dd> - <dt><code>currentValue</code></dt> - <dd>L'elemento corrente in elaborazione nell'array.</dd> - <dt><code>index</code> {{optional_inline}}</dt> - <dd>L'indice dell'elemento corrente in elaborazione nell'array. Inizia dall'indice 0 se viene fornito <code>initialValue</code> Altrimenti, inizia dall'indice 1.</dd> - <dt><code>array</code> {{optional_inline}}</dt> - <dd>L'array a cui viene applicato <code>reduce()</code>.</dd> - </dl> - </dd> - <dt><code>initialValue</code> {{optional_inline}}</dt> - <dd>Un valore da utilizzare come primo argomento della prima chiamata del <code>callback</code>. Se non viene fornito <code>initialValue</code> il primo elemento dell'array verrà utilizzato e saltato. Chiamare <code>reduce()</code> su un array vuoto senza <code>initialValue</code> genererà un <code>TypeError</code>.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Il singolo valore che risulta dalla riduzione.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>reduce()</code> esegue il <code>callback</code> una volta per ogni valore assegnato presente nell'array, prendendo quattro argomenti:</p> - -<ul> - <li><code>accumulator</code></li> - <li><code>currentValue</code></li> - <li><code>currentIndex</code></li> - <li><code>array</code></li> -</ul> - -<p>La prima volta che viene chiamato il callback, <code>accumulator</code> e <code>currentValue</code> possono essere uno dei due valori. Se <code>initialValue</code> viene fornito nella chiamata a <code>reduce()</code>, <code>accumulator</code> sarà uguale a <code>initialValue</code>, e <code>currentValue</code> sarà uguale al primo valore nell'array. Se non viene fornito alcun valore <code>initialValue</code>, <code>accumulator</code> sarà uguale al primo valore dell'array e <code>currentValue</code> sarà uguale al secondo.</p> - -<div class="note"> -<p><strong>Note:</strong> Se non viene fornito <code>initialValue</code>, <code>reduce()</code> eseguirà la funzione di callback a partire dall'indice 1, saltando il primo indice. Se viene fornito <code>initialValue</code>, inizierà dall'indice 0.</p> -</div> - -<p>Se l'array è vuoto e non viene fornito <code>initialValue</code> verrà generato un {{jsxref("TypeError")}}. Se l'array ha solo un elemento (indipendentemente dalla posizione) e non viene fornito <code>initialValue</code>, o se è fornito <code>initialValue</code> ma l'array è vuoto, il valore solo verrà restituito <em>senza</em> chiamare <em><code>callback</code>.</em></p> - -<p>Di solito è più sicuro fornire <code>initialValue</code> perché ci sono tre output possibili senza <code>initialValue</code>, come mostrato nell'esempio seguente.</p> - -<pre class="brush: js notranslate">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 ); -</pre> - -<h3 id="Come_funziona_reduce">Come funziona reduce()</h3> - -<p>Supponiamo che si sia verificato il seguente uso di <code>reduce()</code>:</p> - -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { - return accumulator + currentValue; -}); -</pre> - -<p>Il callback verrebbe invocato quattro volte, con gli argomenti e i valori restituiti in ogni chiamata come segue:</p> - -<table> - <thead> - <tr> - <th scope="col"><code>callback</code></th> - <th scope="col"><code>accumulator</code></th> - <th scope="col"><code>currentValue</code></th> - <th scope="col"><code>currentIndex</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">valore ritornato</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">prima chiamata</th> - <td><code>0</code></td> - <td><code>1</code></td> - <td>1</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>1</code></td> - </tr> - <tr> - <th scope="row">seconda chiamata</th> - <td><code>1</code></td> - <td><code>2</code></td> - <td>2</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>3</code></td> - </tr> - <tr> - <th scope="row">terza chiamata</th> - <td><code>3</code></td> - <td><code>3</code></td> - <td>3</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>6</code></td> - </tr> - <tr> - <th scope="row">quarta chiamata</th> - <td><code>6</code></td> - <td><code>4</code></td> - <td>4</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>10</code></td> - </tr> - </tbody> -</table> - -<p>Il valore restituito da <code>reduce()</code> sarà quello dell'ultima chiamata del callback (<code>10</code>).</p> - -<p>È 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:</p> - -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue ); -</pre> - -<p>Se dovessi fornire <code>initialValue</code> come secondo argomento a <code>reduce()</code>, il risultato sarebbe simile a questo:</p> - -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { - return accumulator + currentValue; -}, 10); -</pre> - -<table> - <thead> - <tr> - <th scope="col"><code>callback</code></th> - <th scope="col"><code>accumulator</code></th> - <th scope="col"><code>currentValue</code></th> - <th scope="col"><code>currentIndex</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">valore restituito</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">prima chiamata</th> - <td><code>10</code></td> - <td><code>0</code></td> - <td><code>0</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>10</code></td> - </tr> - <tr> - <th scope="row">seconda chiamata</th> - <td><code>10</code></td> - <td><code>1</code></td> - <td><code>1</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>11</code></td> - </tr> - <tr> - <th scope="row">terza chiamata</th> - <td><code>11</code></td> - <td><code>2</code></td> - <td><code>2</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>13</code></td> - </tr> - <tr> - <th scope="row">quarta chiamata</th> - <td><code>13</code></td> - <td><code>3</code></td> - <td><code>3</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>16</code></td> - </tr> - <tr> - <th scope="row">quinta chiamata</th> - <td><code>16</code></td> - <td><code>4</code></td> - <td><code>4</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>20</code></td> - </tr> - </tbody> -</table> - -<p>Il valore restituito da <code>reduce()</code> in questo caso sarebbe <code>20</code>.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Sommare_tutti_i_valori_di_un_array">Sommare tutti i valori di un array</h3> - -<pre class="brush: js notranslate">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { - return accumulator + currentValue; -}, 0); -// sum è 6 - -</pre> - -<p>In alternativa scritto con una arrow function:</p> - -<pre class="brush: js notranslate">var total = [ 0, 1, 2, 3 ].reduce( - ( accumulator, currentValue ) => accumulator + currentValue, - 0 -);</pre> - -<h3 id="Somma_dei_valori_in_un_array_di_oggetti">Somma dei valori in un array di oggetti</h3> - -<p>Per riassumere i valori contenuti in un array di oggetti, <strong>devi</strong> fornire <code>initialValue</code>, in modo che ogni elemento passi attraverso la tua funzione</p> - -<pre class="brush: js notranslate">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 -</pre> - -<p>In alternativa scritto con una arrow function:</p> - -<pre class="brush: js notranslate">var initialValue = 0; -var sum = [{x: 1}, {x: 2}, {x: 3}].reduce( - (accumulator, currentValue) => accumulator + currentValue.x - ,initialValue -); - -console.log(sum) // logs 6</pre> - -<h3 id="Appiattire_una_serie_di_array">Appiattire una serie di array</h3> - -<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( - function(accumulator, currentValue) { - return accumulator.concat(currentValue); - }, - [] -); -// flattened is [0, 1, 2, 3, 4, 5] -</pre> - -<p>In alternativa scritto con una arrow function:</p> - -<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( - ( accumulator, currentValue ) => accumulator.concat(currentValue), - [] -); -</pre> - -<h3 id="Conteggio_delle_istanze_di_valori_in_un_oggetto">Conteggio delle istanze di valori in un oggetto</h3> - -<pre class="brush: js notranslate">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 } -</pre> - -<h3 id="Raggruppamento_di_oggetti_in_base_a_una_proprietà">Raggruppamento di oggetti in base a una proprietà</h3> - -<pre class="brush: js notranslate">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 }] -// } -</pre> - -<h3 id="Array_di_legame_contenuti_in_una_serie_di_oggetti_che_utilizzano_lo_spread_operator_e_initialValue">Array di legame contenuti in una serie di oggetti che utilizzano lo spread operator e initialValue</h3> - -<pre class="brush: js notranslate">// 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' -// ]</pre> - -<h3 id="Rimuovi_gli_elementi_duplicati_nellarray">Rimuovi gli elementi duplicati nell'array</h3> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> Se si utilizza un ambiente compatibile con {{jsxref("Set")}} e {{jsxref("Array.from()")}}, è possibile utilizzare <code>let orderedArray = Array.from(new Set(myArray));</code> per ottenere un array in cui sono stati rimossi gli elementi duplicati.</p> -</div> - -<pre class="brush: js notranslate">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);</pre> - -<h3 id="Eseguire_le_Promises_in_Sequenza">Eseguire le Promises in Sequenza</h3> - -<pre class="brush: js notranslate">/** - * 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 -</pre> - -<h3 id="Composizione_funzionale_per_tubazioni">Composizione funzionale per tubazioni</h3> - -<pre class="brush: js notranslate">// 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 - -</pre> - -<h3 id="Scrivere_map_usando_reduce">Scrivere map usando reduce</h3> - -<pre class="brush: js notranslate">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] - -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<pre class="brush: js notranslate">// 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; - } - }); -} -</pre> - -<p>Se hai bisogno di supportare motori JavaScript veramente obsoleti che non supportano <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code>, è meglio non applicare polyfills ai metodi di <code>Array.prototype</code>, poiché non puoi renderli non enumerabili.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.8.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>La tabella di compatibilità in questa pagina è generata a partire da dati strutturati. Se desideri contribuire ai dati, visita <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una pull request.</p> - -<div> -<p>{{Compat("javascript.builtins.Array.reduce")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.reduceRight()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/reverse/index.html b/files/it/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index 750befde61..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>reverse()</strong></code> inverte ua matrice (array) sul posto. Il primo elemento di matrice diventa l'ultima, e l'ultimo elemento di matrice diventa il primo.</p> - -<pre class="brush: js">var a = ['one', 'two', 'three']; -a.reverse(); - -console.log(a); // ['three', 'two', 'one'] -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>a</var>.reverse()</pre> - -<h3 id="Valore_prodotto.">Valore prodotto. </h3> - -<p>La matrice invertita.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo reverse traspone gli elementi della matrice chiamata, <u>mutando la matrice</u>, e restituendo un riferimento alla matrice.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Inversione_degli_elementi_nella_matrice">Inversione degli elementi nella matrice</h3> - -<p>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.</p> - -<pre class="brush: js">var a = ['one', 'two', 'three']; -var reversed = a.reverse(); - -console.log(a); // ['three', 'two', 'one'] -console.log(reversed); // ['three', 'two', 'one'] -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Status</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>definizione iniziale. Implementata in JavaScript 1.1.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Caratteristica</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Edge</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatChrome("1.0")}}</td> - <td>{{CompatGeckoDesktop("1.7")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatIE("5.5")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.join()")}}</li> - <li>{{jsxref("Array.prototype.sort()")}}</li> - <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/slice/index.html b/files/it/web/javascript/reference/global_objects/array/slice/index.html deleted file mode 100644 index 419da77ae4..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/slice/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Array.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/Array/slice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice ---- -<div>{{JSRef}}</div> - -<p><code>Il metodo <strong>slice()</strong></code> ritorna la copia di una porzione dell'array contenente gli elementi compresi tra <code>inzio</code> e <code>fine</code> (<code>fine</code> escluso). Il metodo <strong>slice()</strong> ritorna la copia dell'intero array se non contiene gli elementi di inizio e fine. L'array di partenza non viene modificato.</p> - -<pre class="brush: js">var a = ['zero', 'one', 'two', 'three']; -var sliced = a.slice(1, 3); - -console.log(a); // ['zero', 'one', 'two', 'three'] -console.log(sliced); // ['one', 'two'] -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.slice() -<var>arr</var>.slice(<var>inizio</var>) -<var>arr</var>.slice(<var>inizio</var>, <var>fine</var>) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>begin</code> {{optional_inline}}</dt> - <dd>L'indice zero-based indica da dove inizia l'intervallo da selezionare.</dd> - <dd>Può essere utilizzato un indice negativo, indicante l'offset dall'ultimo elemento dell'array. <code>slice(-2)</code> seleziona gli ultimi due elementi della sequenza.</dd> - <dd>Se <code>begin</code> non viene impostato , <code>slice</code> parte dall'indice <code>0</code>.</dd> - <dt><code>end</code> {{optional_inline}}</dt> - <dd>L' indice zero-base indica dove finisce l'intervallo da selezionare. <code>slice </code>seleziona gli elementi fino a quell'indice ma non l'elemento all'indice <code>end</code>.</dd> - <dd>Per esempio, <code>slice(1,4)</code>estrae dal secondo elemento dell'array al quarto escluso (elementi con indice 1, 2 e 3).</dd> - <dd>Puo essere utilizzato un indice negativo, tale indice indicherebbe l'offset dall'ultimo elemento dell'array. <code>slice(2,-1)</code> estrae dal terzo elemento della sequenza al penuntimo.</dd> - <dd>Se <code>end</code> non viene impostato, <code>slice</code> continua l'estrazione sino al termine dell'array (<code>arr.length</code>).</dd> - <dd>Se <code>end</code> è maggiore della lunghezza della sequenza , <code>slice</code> continua l'estrazione sino al termine dell'array (<code>arr.length</code>).</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<p>Un nuovo array che contiene gli elementi estratti.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>slice</code> 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:</p> - -<ul> - <li>Per i riferimenti a oggetti (e non i veri e propri oggetti), <code>slice</code> copia i riferimenti nel nuovo array. Entrambi gli array riferiscono quindi lo stesso oggetto. Se un oggetto riferito viene modificato, le modifiche interessano entrambi gli array.</li> - <li>Per le stringhe, i numeri e i boolean (non oggetti {{jsxref("String")}}, {{jsxref("Number")}} e {{jsxref("Boolean")}} <code>slice</code> copia i valori nel nuovo array. Le modifiche alle stringhe, ai numeri e ai boolean in un array non interessano l'altro array.</li> -</ul> - -<p>Se viene aggiunto un nuovo elemento in uno degli array, l'altro non viene modificato.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Restituire_una_porzione_dellarray_esistente">Restituire una porzione dell'array esistente</h3> - -<pre class="brush: js">var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; -var citrus = fruits.slice(1, 3); - -// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] -// citrus contains ['Orange','Lemon'] -</pre> - -<h3 id="Utilizzare_slice">Utilizzare <code>slice</code></h3> - -<p>Nell'esempio che segue, <code>slice</code> crea un nuovo array, <code>newCar</code>, da <code>myCar</code>. Entrambi includono un riferimento all'oggetto <code>myHonda</code>. Quando il colore di <code>myHonda</code> diventa viola, entrambi gli array riflettono la modifica.</p> - -<pre class="brush: js">// 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); -</pre> - -<p>Lo script scrive:</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Oggetti_Array-like">Oggetti Array-like</h2> - -<p>Il metodo <code>slice</code> 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'.</p> - -<pre class="brush: js">function list() { - return Array.prototype.slice.call(arguments); -} - -var list1 = list(1, 2, 3); // [1, 2, 3] -</pre> - -<p>Il binding può essere effettuato con la funzione .<code>call</code> di {{jsxref("Function.prototype")}}<span style="font-size: 1rem; letter-spacing: -0.00278rem;"> e può anche essere ridotto utilizzando </span><code style="font-size: 1rem; letter-spacing: -0.00278rem;">[].slice.call(arguments)</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;"> invece di </span><code style="font-size: 1rem; letter-spacing: -0.00278rem;">Array.prototype.slice.call</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">. Ad ogni modo, può essere semplificato utilizzando {{jsxref("Function.prototype.bind", "bind")}}.</span></p> - -<pre class="brush: js">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] -</pre> - -<h2 id="Streamlining_cross-browser_behavior">Streamlining cross-browser behavior</h2> - -<p>Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by <code>Array.prototype.slice</code> 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 <em>de facto</em> standard behavior. (The shim also fixes IE to work with the second argument of <code>slice()</code> 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.)</p> - -<pre class="brush: js">/** - * 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; - }; - } -}()); -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Initial definition. Implemented in JavaScript 1.2.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.slice")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Array.prototype.splice()")}}</li> - <li>{{jsxref("Function.prototype.call()")}}</li> - <li>{{jsxref("Function.prototype.bind()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/some/index.html b/files/it/web/javascript/reference/global_objects/array/some/index.html deleted file mode 100644 index 3befa8a8b0..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/some/index.html +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Array.prototype.some() -slug: Web/JavaScript/Reference/Global_Objects/Array/some -translation_of: Web/JavaScript/Reference/Global_Objects/Array/some ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>some()</strong></code> verifica se almeno un elemento nell'array passa la verifica implementata dalla funzione fornita.</p> - -<div class="note"> -<p><strong>Note</strong>: Questo metodo ritorna <code>false</code> per qualsiasi condizione passata ad un array vuoto.</p> -</div> - - - -<div>{{EmbedInteractiveExample("pages/js/array-some.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.some(<var>callback</var>[, <var>thisArg</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione di test per ogni elemento, prende tre elementi: - <dl> - <dt><code>valoreCorrente</code></dt> - <dd>Il valore corrente dell'elemento che deve essere processato nell'array.</dd> - <dt><code>indice</code> {{Optional_inline}}</dt> - <dd>l'indice dell'elemento corrente dell'array.</dd> - <dt><code>array</code>{{Optional_inline}}</dt> - <dd>l'array completo alla quale è stato chiamato il <code>some().</code></dd> - </dl> - </dd> - <dt><code>thisArg</code>{{Optional_inline}}</dt> - <dd>Valore da usare come <code>this</code> quando si esegue la <code>callback</code>.</dd> -</dl> - -<h3 id="Valore_ritornato">Valore ritornato</h3> - -<p><code><strong>true</strong></code> se la funzione di callback ha ritornato un valore {{Glossary("truthy")}} per almeno un elemento nell'array; altrimenti, <code><strong>false</strong></code>.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>some()</code> esegue la funzione di <code>callback</code> per ogni elemento presente nell'array finchè non ne trova uno dove la <code>callback</code> retorna un valore <em>truthy</em> (un valore che ritorna <code>true</code> se convertito in un Booleano). Se viene trovato un elemento di questo genere allora <code>some()</code> ritorna immediatamente <code>true</code>. altrimenti, <code>some()</code> ritorna <code>false</code>. <code>callback</code> viene invocato solamente solamente per gli elementi che hanno un valore assegnato; quindi non viene chiamato per elementi eliminati o mai assegnati.</p> - -<p><code>callback</code> è invocato con tre argomenti: il valore dell'elemento, l'indice dell'elemento nell'array, e l'array dalla quale è stato invocato.</p> - -<p>se viene passato un parametro <code>thisArg</code> al metodo <code>some()</code>, verrà usato come valore <code>this</code> per le callbacks. altrimenti, verrà usato il valore {{jsxref("undefined")}} come valore di <code>this</code>. Il valore di <code>this</code> nella <code>callback</code> è determinato in accordo con <a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/this">le normali regole per determinare il valore di this nelle funzioni</a>.</p> - -<p><code>some()</code> non muta l'array dalla quale è stato evocato.</p> - -<p>Il range di elementi processati da <code>some()</code> è impostato prima della prima chiamata alla <code>callback</code>. Gli elementi che vengono attaccati o aggiunti all'array dopo che è stata effettuata la chiamata al metodo <code>some()</code> non verranno tenuti in considerazione. Se al contrario un elemento viene cambiato prima che venga processato dalla <code>callback</code>, il valore passato sarà quello modificato. Elementi eliminati invece non verranno controllati. </p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Testare_i_valori_all'interno_di_un_array">Testare i valori all'interno di un array</h3> - -<p>L'esempio seguente testa se almeno un elemento dell'array è maggiore di 10.</p> - -<pre class="brush: js">function isBiggerThan10(element, index, array) { - return element > 10; -} - -[2, 5, 8, 1, 4].some(isBiggerThan10); // false -[12, 5, 8, 1, 4].some(isBiggerThan10); // true -</pre> - -<h3 id="Testing_array_elements_using_arrow_functions">Testing array elements using arrow functions</h3> - -<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> provide a shorter syntax for the same test.</p> - -<pre class="brush: js">[2, 5, 8, 1, 4].some(x => x > 10); // false -[12, 5, 8, 1, 4].some(x => x > 10); // true -</pre> - -<h3 id="Checking_whether_a_value_exists_in_an_array">Checking whether a value exists in an array</h3> - -<p>To mimic the function of the <code>includes()</code> method, this custom function returns <code>true</code> if the element exists in the array:</p> - -<pre class="brush: js">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</pre> - -<h3 id="Checking_whether_a_value_exists_using_an_arrow_function">Checking whether a value exists using an arrow function</h3> - -<pre class="brush: js">var fruits = ['apple', 'banana', 'mango', 'guava']; - -function checkAvailability(arr, val) { - return arr.some(arrVal => val === arrVal); -} - -checkAvailability(fruits, 'kela'); // false -checkAvailability(fruits, 'banana'); // true</pre> - -<h3 id="Converting_any_value_to_Boolean">Converting any value to Boolean</h3> - -<pre class="brush: js">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</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p><code>some()</code> 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 <code>some()</code> 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 <code>fun.call</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> - -<pre class="brush: js">// 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; - }; -} -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.some")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Array.prototype.find()")}}</li> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>{{jsxref("Array.prototype.every()")}}</li> - <li>{{jsxref("TypedArray.prototype.some()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/sort/index.html b/files/it/web/javascript/reference/global_objects/array/sort/index.html deleted file mode 100644 index 6c16c7dd6b..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/sort/index.html +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: Array.prototype.sort() -slug: Web/JavaScript/Reference/Global_Objects/Array/sort -tags: - - Array - - JavaScript - - Metodi - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>sort()</strong></code> ordina gli elementi di un array <em><a href="https://en.wikipedia.org/wiki/In-place_algorithm">in place</a></em> e ritorna l'array. L'ordinamento non è necessariamente <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable</a>. L'ordinamento predefinito è in base ai punti di codice Unicode della stringa.</p> - -<p>Il tempo e la complessità dell'ordinamento dipendono dall'implementazione, perciò non possono essere garantiti.</p> - -<pre class="brush: js">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. -</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.sort() -<var>arr</var>.sort(<var>[compareFunction]</var>) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>compareFunction</code> {{optional_inline}}</dt> - <dd>Specifica una funzione che definisce il tipo di ordinamento. Se viene omessa, l'array è ordinato in base ai valori dei suoi caratteri <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">Unicode</a> code , basandosi sulle stringhe di ogni elemento convertito.</dd> -</dl> - -<h3 id="Valore_ritornato">Valore ritornato</h3> - -<p>L'array ordinato. Nota che l'array è ordinato <em><a href="https://en.wikipedia.org/wiki/In-place_algorithm">in place</a></em>, e non viene fatta alcuna copia.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Se non viene fornita una <code>compareFunction</code> , 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.</p> - -<p>Se viene fornita una <code>compareFunction</code> , 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:</p> - -<ul> - <li>Se <code>compareFunction(a, b)</code> è minore di 0, posiziona <code>a</code> in un indice inferiore di <code>b</code>, quindi <code>a</code> viene prima.</li> - <li>Se <code>compareFunction(a, b)</code> ritorna 0, lascia <code>a</code> e <code>b</code> invariati l'uno rispetto all'altro, ma ordinati rispetto a tutti i diversi elementi. Nota: lo standard ECMAscript non garantisce questo comportamento, quindi non tutti i browser (ad esempio versioni di Mozilla risalenti almeno al 2003) rispettano questo.</li> - <li>Se <code>compareFunction(a, b)</code> è maggiore di 0, posiziona <code>b</code> con un indice più basso di <code>a</code>, cioè <code>b</code> viene prima.</li> - <li><code>compareFunction(a, b)</code> deve sempre restituire lo stesso valore quando viene data una coppia specifica di elementi a e b come i suoi due argomenti. Se vengono restituiti risultati non coerenti, l'ordinamento non è definito.</li> -</ul> - -<p>Quindi, la funzione di confronto ha la seguente forma:</p> - -<pre class="brush: js">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; -} -</pre> - -<p>Per confrontare i numeri anziché le stringhe, la funzione di confronto può semplicemente sottrarre <code>b</code> da <code>a</code>. La seguente funzione ordinerà l'array in ordine crescente (se non contiene <code>Infinity</code> e <code>NaN</code>):</p> - -<pre class="brush: js">function compareNumbers(a, b) { - return a - b; -} -</pre> - -<p>Il metodo <code>sort</code> può essere usato bene con {{jsxref("Operators/function", "function expressions", "", 1)}} ( e <a href="/en-US/docs/Web/JavaScript/Guide/Closures">closures</a>):</p> - -<pre class="brush: js">var numbers = [4, 2, 5, 1, 3]; -numbers.sort(function(a, b) { - return a - b; -}); -console.log(numbers); - -// [1, 2, 3, 4, 5] -</pre> - -<p>ES2015 fornisce le {{jsxref("Functions_and_function_scope/Arrow_functions", "arrow function", "", 1)}}, che consentono una sintassi più compatta:</p> - -<pre class="brush: js">let numbers = [4, 2, 5, 1, 3]; -numbers.sort((a, b) => a - b); -console.log(numbers); - -// [1, 2, 3, 4, 5]</pre> - -<p>Gli Object possono essere ordinati passando il valore di una delle loro proprietà.</p> - -<pre class="brush: js">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; -});</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Creare_visualizzare_ed_ordinare_un_array">Creare, visualizzare, ed ordinare un array</h3> - -<p>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 .</p> - -<pre class="brush: js">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)); -</pre> - -<p>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.</p> - -<pre>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 -</pre> - -<h3 id="Ordinare_caratteri_non-ASCII">Ordinare caratteri non-ASCII </h3> - -<p>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.</p> - -<pre class="brush: js">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é'] -</pre> - -<h3 id="Ordinare_con_map">Ordinare con map</h3> - -<p>La <code>compareFunction</code> può essere invocata più volte per elemento all'interno dell'array. In base alla natura della <code>compareFunction</code>, si potrebbe produrre un sovraccarico elevato. Maggiore è il lavoro svolto da <code>compareFunction</code> e maggiori sono gli elementi da ordinare, potrebbe essere saggio utilizzare una <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> 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.</p> - -<pre class="brush: js" dir="rtl">// 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]; -}); -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Osservazione</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_il_browser">Compatibilità con il browser</h2> - -<div> -<div class="hidden">La tabella di compatibilità in questa pagina è generata da dati strutturati. Se desideri contribuire ai dati, consulta <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una richiesta di pull.</div> - -<p>{{Compat("javascript.builtins.Array.sort")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.reverse()")}}</li> - <li>{{jsxref("String.prototype.localeCompare()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/splice/index.html b/files/it/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index a68058baf8..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -tags: - - Aggiunta - - Array - - JavaScript - - Method - - Prototype - - Reference - - Rimozione - - splice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong><code>splice()</code></strong> modifica il contenuto di un array rimuovendo o sostituendo elementi esistenti e/o aggiungendo nuovi elementi <a href="https://en.wikipedia.org/wiki/In-place_algorithm">in place</a>.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-splice.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>var arrDeletedItems = array</var>.splice(<var>start[</var>, <var>deleteCount[</var>, <var>item1[</var>, <var>item2[</var>, <em>...]]]]</em>) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>start</code></dt> - <dd>L'indice al quale iniziare a cambiare l'array. Se maggiore della lunghezza dell'array, <code>start</code> 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 <code>array.length - n</code>). Se il valore assoluto di <code>start</code> è maggiore della lunghezza dell'array, inizierà dall'indice 0.</dd> - <dt><code>deleteCount</code> {{optional_inline}}</dt> - <dd>Un numero intero che indica il numero di elementi nell'array da rimuovere da <code>start</code>.</dd> - <dd>Se <code>deleteCount</code> viene omesso, o se il suo valore è uguale o maggiore di <code>array.length - start</code> (cioè, se è uguale o maggiore del numero di elementi rimasti nell'array, a partire da <code>start</code>), tutti gli elementi da <code>start</code> alla fine dell'array verranno eliminati.</dd> - <dd>Se <code>deleteCount</code> è 0 o negativo, non vengono rimossi elementi. In questo caso, devi specificare almeno un nuovo elemento (vedi sotto).</dd> - <dt><code>item1, item2, <em>...</em></code> {{optional_inline}}</dt> - <dd>Gli elementi da aggiungere all'array, a partire da <code>start</code>. Se non viene specificato alcun elemento, <code>splice()</code> rimuoverà solo gli elementi dall'array.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>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.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Rimuovi_0_(zero)_elementi_dall'indice_2_e_inserisci_drum">Rimuovi 0 (zero) elementi dall'indice 2 e inserisci "drum"</h3> - -<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; -var removed = myFish.splice(2, 0, 'drum'); - -// myFish è ["angel", "clown", "drum", "mandarin", "sturgeon"] -// removed è [], nessun elemento rimosso</pre> - -<h3 id="Rimuovi_0_(zero)_elementi_dall'indice_2_e_inserisci_drum_e_guitar">Rimuovi 0 (zero) elementi dall'indice 2 e inserisci "drum" e "guitar"</h3> - -<pre class="brush: js">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 -</pre> - -<h3 id="Rimuovi_1_elemento_dall'indice_3">Rimuovi 1 elemento dall'indice 3</h3> - -<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; -var removed = myFish.splice(3, 1); - -// removed è ["mandarin"] -// myFish è ["angel", "clown", "drum", "sturgeon"] -</pre> - -<h3 id="Rimuovi_1_elemento_dall'indice_2_e_inserisci_trumpet">Rimuovi 1 elemento dall'indice 2 e inserisci "trumpet"</h3> - -<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'sturgeon']; -var removed = myFish.splice(2, 1, 'trumpet'); - -// myFish è ["angel", "clown", "trumpet", "sturgeon"] -// removed è ["drum"]</pre> - -<h3 id="Rimuovere_2_elementi_dall'indice_0_e_inserire_parrot_anemone_e_blue">Rimuovere 2 elementi dall'indice 0 e inserire "parrot", "anemone" e "blue"</h3> - -<pre class="brush: js">var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; -var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); - -// myFish è ["parrot", "anemone", "blue", "trumpet", "sturgeon"] -// removed è ["angel", "clown"]</pre> - -<h3 id="Rimuovere_2_elementi_dall'indice_2">Rimuovere 2 elementi dall'indice 2</h3> - -<pre class="brush: js">var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; -var removed = myFish.splice(myFish.length - 3, 2); - -// myFish è ["parrot", "anemone", "sturgeon"] -// removed è ["blue", "trumpet"]</pre> - -<h3 id="Rimuovere_1_elemento_dall'indice_-2">Rimuovere 1 elemento dall'indice -2</h3> - -<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; -var removed = myFish.splice(-2, 1); - -// myFish è ["angel", "clown", "sturgeon"] -// removed è ["mandarin"]</pre> - -<h3 id="Rimuovere_tutti_gli_elementi_dopo_l'indice_2_(incl.)">Rimuovere tutti gli elementi dopo l'indice 2 (incl.)</h3> - -<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; -var removed = myFish.splice(2); - -// myFish è ["angel", "clown"] -// removed è ["mandarin", "sturgeon"]</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.2.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.splice")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.push()", "push()")}} / {{jsxref("Array.prototype.pop()", "pop()")}} — aggiunge/rimuove elementi dalla fine dell'array</li> - <li>{{jsxref("Array.prototype.unshift()", "unshift()")}} / {{jsxref("Array.prototype.shift()", "shift()")}} — aggiunge/rimuove elementi dall'inizio dell'array</li> - <li>{{jsxref("Array.prototype.concat()", "concat()")}} — restituisce un nuovo array composto da questo array unito ad altri array e/o valore/i</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/tostring/index.html b/files/it/web/javascript/reference/global_objects/array/tostring/index.html deleted file mode 100644 index a5b8dcaa1e..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/tostring/index.html +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Array.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Array/toString -tags: - - Array - - JavaScript - - Prototype - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>toString()</strong></code> restituisce una stringa che rappresenta l'array specificato e i suoi elementi.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-tostring.html")}}</div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.toString()</pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Una stringa che rappresenta gli elementi dell'array.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>L'oggetto {{jsxref("Array")}} sovrascrive il metodo <code>toString</code> di {{jsxref("Object")}}. Per gli oggetti Array, il metodo <code>toString</code> unisce l'array e restituisce una stringa contenente ciascun elemento dell'array separato da virgole.</p> - -<p>JavaScript chiama automaticamente il metodo <code>toString</code> quando un array deve essere rappresentato come un valore di testo o quando viene fatto riferimento a un array in una concatenazione di stringhe.</p> - -<h3 id="ECMAScript_5_semantics">ECMAScript 5 semantics</h3> - -<p>A partire da JavaScript 1.8.5 (Firefox 4) e coerente con la semantica ECMAScript 5th edition, il metodo <code>toString()</code> è generico e può essere utilizzato con qualsiasi oggetto. {{jsxref("Object.prototype.toString()")}} sarà chiamato e verrà restituito il valore risultante.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.1.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.2', 'Array.prototype.toString')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.toString")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.join()")}}</li> - <li>{{jsxref("Object.prototype.toSource()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/unshift/index.html b/files/it/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index ca4597e973..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -<div>{{JSRef}}</div> - -<div>Il metodo <strong><code>unshift()</code></strong> aggiunge uno o più elementi all'inizio di un array e restitusce la nuova lunghezza dell'array stesso.</div> - -<div> </div> - -<div>{{EmbedInteractiveExample("pages/js/array-unshift.html")}}</div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.unshift(<var>element1</var>[, ...[, <var>elementN</var>]])</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>element<em>N</em></code></dt> - <dd>Gli elementi da aggiungere all'inizio dell'array.</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<dl> - <dd>La nuova proprietà {{jsxref("Array.length", "length")}} dell'oggetto su cui è stato chiamato il metodo.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>unshift</code> inserisce i valori passati come parametri all'inizio di un oggetto array-like.</p> - -<p><code>unshift</code> è 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à <code>length</code> che rifletta l'ultimo di una serie di consecutive proprietà numeriche zero-based potrebbero non comportarsi in alcun modo significativo.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">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] -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Initial definition. Implemented in JavaScript 1.2.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.unshift")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Array.prototype.push()")}}</li> - <li>{{jsxref("Array.prototype.pop()")}}</li> - <li>{{jsxref("Array.prototype.shift()")}}</li> - <li>{{jsxref("Array.prototype.concat()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/array/values/index.html b/files/it/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index f3019ef144..0000000000 --- a/files/it/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p><code style=""><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Il metodo </span></font><strong>values()</strong></code> restituisce un nuovo oggetto <strong><code>Array Iterator</code></strong> che contiene i valori per ogni indice nell'array.</p> - -<p>{{EmbedInteractiveExample("pages/js/array-values.html")}}</p> - -<pre class="brush: js">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</pre> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>arr</var>.values()</pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un nuovo oggetto iteratore {{jsxref("Array")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Iterazione_utilizzando_il_for...of_loop">Iterazione utilizzando il <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> loop</h3> - -<pre class="brush: js">var arr = ['a', 'b', 'c', 'd', 'e']; -var iterator = arr.values(); - -for (let letter of iterator) { - console.log(letter); -} -</pre> - -<p><strong>Array.prototype.values</strong> è una implementazionde di default di <strong>Array.prototype[Symbol.iterator]</strong>.</p> - -<pre>Array.prototype.values === Array.prototype[Symbol.iterator] //true</pre> - -<p><strong>TODO</strong>: please write about why we need it, use cases.</p> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.values")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Array.prototype.keys()")}}</li> - <li>{{jsxref("Array.prototype.entries()")}}</li> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>{{jsxref("Array.prototype.every()")}}</li> - <li>{{jsxref("Array.prototype.some()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/arraybuffer/index.html b/files/it/web/javascript/reference/global_objects/arraybuffer/index.html deleted file mode 100644 index 118b3d2801..0000000000 --- a/files/it/web/javascript/reference/global_objects/arraybuffer/index.html +++ /dev/null @@ -1,147 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>L'oggetto <code>ArrayBuffer</code> viene utilizzato per rappresentare un buffer di lunghezza fissa di dati non elaborati. Non è possibile manipolare il contenuto di un <code>ArrayBuffer</code>, è 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.</p> - -<div>{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">new ArrayBuffer(length) -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>length</code></dt> - <dd>La dimensione, in bytes, dell'array buffer da creare.</dd> -</dl> - -<h3 id="Valori_di_ritorno">Valori di ritorno</h3> - -<p>Un nuovo oggetto di tipo <code>ArrayBuffer</code> della dimensione specificata. Il suo contenuto è inzializzato a 0.</p> - -<h3 id="Eccezioni">Eccezioni</h3> - -<p>Un {{jsxref("RangeError")}} viene generato se la lunghezza è maggiore di di {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) oppure è negativa.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il costruttore <code>ArrayBuffer</code> crea un nuovo <code>ArrayBuffer</code> di lunghezza specificata in bytes.</p> - -<h3 id="Ottenere_un_array_buffer_da_dati_pre-esistenti">Ottenere un array buffer da dati pre-esistenti</h3> - -<ul> - <li><a href="/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">Da una stringa in Base64</a></li> - <li><a href="/en-US/docs/Web/API/FileReader#readAsArrayBuffer()">Da un file locale</a></li> -</ul> - -<h2 id="Proprietà">Proprietà</h2> - -<dl> - <dt><code>ArrayBuffer.length</code></dt> - <dd>La dimensione del costruttore <code>ArrayBuffer</code> il cui valore è 1.</dd> - <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> - <dd>La funzione costruttore utilizzata per creare oggetti derivati.</dd> - <dt>{{jsxref("ArrayBuffer.prototype")}}</dt> - <dd>Permette di aggiungere proprietà a tutti gli oggetti di tipo <code>ArrayBuffer</code>.</dd> -</dl> - -<h2 id="Metodi">Metodi</h2> - -<dl> - <dt>{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}</dt> - <dd>Restituisce <code>true</code> se <code>args</code> è una delle viste di ArrayBuffer, come un array di oggetti tipizzato o un {{jsxref("DataView")}}. Altrimenti restituisce <code>false</code>.</dd> - <dt>{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}</dt> - <dd>Restituisce un nuovo <code>ArrayBuffer</code> i cui contenuti sono presi dai dati dell'oggetto <code>oldBuffer</code> e successivamente troncato o esteso a zero tramite <code>newByteLength</code>.</dd> -</dl> - -<h2 id="Istanze">Istanze</h2> - -<p>Tutte le istanze di ArrayBuffer ereditano da {{jsxref("ArrayBuffer.prototype")}}.</p> - -<h3 id="Proprietà_2">Proprietà</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}</p> - -<h3 id="Metodi_2">Metodi</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}</p> - -<dl> - <dt>{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}</dt> - <dd>Esegue le stesse operazioni di {{jsxref("ArrayBuffer.prototype.slice()")}}.</dd> -</dl> - -<h2 id="Esempio">Esempio</h2> - -<p>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</p> - -<pre class="brush: js">var buffer = new ArrayBuffer(8); -var view = new Int32Array(buffer);</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Typed Array')}}</td> - <td>{{Spec2('Typed Array')}}</td> - <td>Sostituito da ECMAScript 6.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> - <p>Definizione iniziale con standard ECMA. Specifica che <code>new</code> è richiesto.</p> - </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.ArrayBuffer")}}</p> - -<h2 id="Note_sulla_compatibilità">Note sulla compatibilità</h2> - -<p>Con ECMAScript 2015, ArrayBuffer deve essere inizializzato con l'operatore {{jsxref("Operators/new", "new")}}. Inizializzare ArrayBuffer senza l'operatore new genererà un {{jsxref("TypeError")}}.</p> - -<pre class="brush: js example-bad">var dv = ArrayBuffer(10); -// TypeError: inizializzaree un ArrayBuffer senza il costruttore new -// genererà un errore -</pre> - -<pre class="brush: js example-good">var dv = new ArrayBuffer(10);</pre> - -<h2 id="Leggi_anche">Leggi anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></li> - <li>{{jsxref("SharedArrayBuffer")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/atomics/index.html b/files/it/web/javascript/reference/global_objects/atomics/index.html deleted file mode 100644 index 56c3ed5ecc..0000000000 --- a/files/it/web/javascript/reference/global_objects/atomics/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Atomics -slug: Web/JavaScript/Reference/Global_Objects/Atomics -translation_of: Web/JavaScript/Reference/Global_Objects/Atomics ---- -<div>{{JSRef}}</div> - -<p>L' oggetto <strong><code>Atomics</code></strong> fornisce operazioni atomiche come metodi statici. Sono utilizzati con gli oggetti {{jsxref("SharedArrayBuffer")}}.</p> - -<p>Le operazioni atomiche sono implementate nel modulo <code>Atomics</code>. Diversamente dagli altri oggetti global, <code>Atomics</code> non è un constructor. Non è, quindi, possibile utilizzarlo con <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> o invocare l'oggetto <code>Atomics</code> come una funzione. Tutte le proprietà ed i metodi di <code>Atomics</code> sono statici (come per esempio nel caso dell'oggetto {{jsxref("Math")}}).</p> - -<h2 id="Propertà">Propertà</h2> - -<dl> - <dt><code>Atomics[Symbol.toStringTag]</code></dt> - <dd>Il valore di questa proprietà è "Atomics".</dd> -</dl> - -<h2 id="Metodi">Metodi</h2> - -<h3 id="Operazioni_Atomiche">Operazioni Atomiche</h3> - -<p>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.</p> - -<dl> - <dt>{{jsxref("Atomics.add()")}}</dt> - <dd>Aggiunge un determinato valore in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.</dd> - <dt>{{jsxref("Atomics.and()")}}</dt> - <dd>Calcola un "bitwise AND" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.</dd> - <dt>{{jsxref("Atomics.compareExchange()")}}</dt> - <dd>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.</dd> - <dt>{{jsxref("Atomics.exchange()")}}</dt> - <dd>Memorizza un dato valore in una determinata posizione nell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.</dd> -</dl> - -<dl> - <dt>{{jsxref("Atomics.load()")}}</dt> - <dd>Restituisce il valore di una determinata posizione nell'array.</dd> - <dt>{{jsxref("Atomics.or()")}}</dt> - <dd>Calcola un "bitwise OR" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.</dd> - <dt>{{jsxref("Atomics.store()")}}</dt> - <dd>Memorizza un dato valore in una determinata posizione dell'array. Restituisce lo stesso valore momorizzato.</dd> - <dt>{{jsxref("Atomics.sub()")}}</dt> - <dd>Sottrae un determinato valore ad una data posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.</dd> - <dt>{{jsxref("Atomics.xor()")}}</dt> - <dd>Calcola un "bitwise XOR" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.</dd> -</dl> - -<h3 id="Wait_and_wake">Wait and wake</h3> - -<p>I metodi <code>wait()</code> e <code>wake() </code>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.</p> - -<dl> - <dt>{{jsxref("Atomics.wait()")}}</dt> - <dd> - <p>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 <code>"ok"</code>, <code>"not-equal"</code>, oppure <code>"timed-out"</code>. Se l'attesa non è consentita dall'agente che effettua la chiamata, allora il metodo innesca una "Error Exception" (molti browsers non consentiranno <code>wait()</code> nel loro thread principale)</p> - </dd> - <dt>{{jsxref("Atomics.wake()")}}</dt> - <dd>"Sveglia" gli agenti dormienti nella coda di wait in una determinata posizione dell'array. Restituisce il numero degli agenti "svegliati".</dd> - <dt>{{jsxref("Atomics.isLockFree()", "Atomics.isLockFree(size)")}}</dt> - <dd> - <p>Un primitiva di ottimizzazione che può essere utilizzata per determinare quando utilizzare "lock" o operazioni atomiche. Restituisce <code>true</code>, se un operazione atomica su un array di una data dimensione può essere implementata utilizzando operazioni atomiche hardware (invece del "lock"). Solo per esperti.</p> - </dd> -</dl> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Status</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-atomics-object', 'Atomics')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td>Definizione Iniziale in ES2017.</td> - </tr> - <tr> - <td>{{SpecName('ES8', '#sec-atomics-object', 'Atomics')}}</td> - <td>{{Spec2('ES8')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_Browser">Compatibilità con i Browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}} [2]</td> - <td>{{CompatGeckoDesktop("55")}} [1]</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatGeckoMobile("55")}} [1]</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] In Firefox, dalla versione 46 alla versione 54 questa feature è disabilitata da una configurazione avenzata. In about:config, configurare <code>javascript.options.shared_memory</code> a <code>true</code>. </p> - -<p>[2] L' implementazione è in via di sviluppo e richiede i flag di runtime: <code>--js-flags=--harmony-sharedarraybuffer --enable-blink-feature=SharedArrayBuffer</code></p> - -<h2 id="Note_di_Compatibilità">Note di Compatibilità</h2> - -<p>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:</p> - -<ul> - <li>I metodi <code>Atomics.futexWakeOrRequeue()</code> e <code>Atomics.fence()</code> sono stati completamente rimossi ({{bug(1259544)}} e {{bug(1225028)}}).</li> - <li>I metodi {{jsxref("Atomics.wait()")}} e {{jsxref("Atomics.wake()")}} sono sati chiamati <code>Atomics.futexWait()</code> e <code>Atomics.futexWake()</code> ({{bug(1260910)}}). Nota: I vecchi nomi sono stati rimossi nella versione 49 e successive ({{bug(1262062)}}).</li> - <li>Le proprietà <code>Atomics.OK</code>, <code>Atomics.TIMEDOUT</code>, <code>Atomics.NOTEQUAL</code> sono state rimosse. Il metodo {{jsxref("Atomics.wait()")}} adesso restituisce le stringhe "ok", "timed-out" e "not-equal" ({{bug(1260835)}}).</li> - <li> - <p>Il parametro <code>count</code> del metodo {{jsxref("Atomics.wake()")}} è stato cambiato: il valore di default adesso è <code>+Infinity</code>, e non <code>0</code> ({{bug(1253350)}}).</p> - </li> -</ul> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("ArrayBuffer")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></li> - <li><a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a></li> - <li><a href="https://github.com/lars-t-hansen/parlib-simple">parlib-simple </a>– a simple library providing synchronization and work distribution abstractions.</li> - <li><a href="https://github.com/tc39/ecmascript_sharedmem/blob/master/TUTORIAL.md">Shared Memory – a brief tutorial</a></li> - <li><a href="https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/">A Taste of JavaScript’s New Parallel Primitives – Mozilla Hacks</a></li> -</ul> 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 deleted file mode 100644 index 5c8a466c0f..0000000000 --- a/files/it/web/javascript/reference/global_objects/atomics/store/index.html +++ /dev/null @@ -1,91 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo statico <code><strong>Atomics</strong></code><strong><code>.store()</code></strong> memorizza un determinato valore nella posizione data nell'array e restituisce quel valore.</p> - -<div>{{EmbedInteractiveExample("pages/js/atomics-store.html")}}</div> - -<p class="hidden">La fonte per questo esempio interattivo è memorizzata in un repository GitHub. Se desideri contribuire al progetto di esempi interattivi, clonare <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviarci una richiesta di pull</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">Atomics.store(typedArray, indice, valore) -</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>typedArray</code></dt> - <dd>Un array con numero intero condiviso. Uno di {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, o {{jsxref("Uint32Array")}}.</dd> - <dt><code>indice </code></dt> - <dd>La posizione in <code>typedArray</code> per memorizzare un <code>value</code> in.</dd> - <dt><code>valore</code></dt> - <dd>Numero da memorizzare.</dd> -</dl> - -<h3 id="Valore_di_Ritorno">Valore di Ritorno</h3> - -<p>The value that has been stored<br> - // Il valore memorizzato.</p> - -<h3 id="Eccezioni">Eccezioni</h3> - -<ul> - <li>Genera un {{jsxref("TypeError")}}, se <code>typedArray</code> non è uno dei tipi di numeri consentiti.</li> - <li>Genera un {{jsxref("TypeError")}}, se <code>typedArray</code> non è un tipo di array tipizzato condiviso.</li> - <li>Genera un {{jsxref("RangeError")}}, se <code>indice</code> è fuori limite in <code>typedArray</code>.</li> -</ul> - -<h2 id="Esempio">Esempio</h2> - -<pre class="brush: js">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]); - -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazioni</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-atomics.store', 'Atomics.store')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td>definizione inizile in ES2017.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibili">Browser compatibili</h2> - -<div class="hidden">La tabella di compatibilità in questa pagina è generata da dati strutturati. Se desideri contribuire ai dati, consulta <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una richiesta di pull</div> - -<p>{{Compat("javascript.builtins.Atomics.store")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Atomics")}}</li> - <li>{{jsxref("Atomics.load()")}}</li> -</ul> 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 deleted file mode 100644 index 32c3d5fa57..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/getdate/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Date.prototype.getDate() -slug: Web/JavaScript/Reference/Global_Objects/Date/getDate -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong><code>getDate()</code></strong> resituisce il giorno del mese per la data specificata in accordo con l'ora locale.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-getdate.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getDate()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero integer, tra 1 e 31, rappresentante il giorno del mese per la data fornita in accordo con l'ora locale.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getDate()">Utilizzando getDate()</h3> - -<p>La seconda dichiarazione qui sotto assegna il valore 25 alla variabile <code>day</code>, basata sul valore dell'oggetto {{jsxref("Date")}} <code>Xmas95</code>.</p> - -<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); -var day = Xmas95.getDate(); - -console.log(day); // 25 -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.1.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getDate")}}</p> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> - <li>{{jsxref("Date.prototype.getUTCDay()")}}</li> - <li>{{jsxref("Date.prototype.setDate()")}}</li> -</ul> 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 deleted file mode 100644 index c5fd48bca7..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/getday/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Date.prototype.getDay() -slug: Web/JavaScript/Reference/Global_Objects/Date/getDay -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay ---- -<div>{{JSRef}}</div> - -<p><span class="seoSummary">Il metodo <strong><code>getDay()</code></strong> restituisce il giorno della settimana per la data specificata in accordo con l'ora locale, dove 0 rappresenta Domenica.</span> Per il giorno del mese, vedere {{jsxref("Date.prototype.getDate()")}}.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-getday.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getDay()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getDay()">Utilizzando <code>getDay()</code></h3> - -<p>La seconda dichiarazione qui sotto assegna il valore 1 a <code>weekday</code>, basato sul valore dell'oggetto {{jsxref("Date")}} <code>Xmas95</code>. December 25, 1995, è un Lunedi.</p> - -<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); -var weekday = Xmas95.getDay(); - -console.log(weekday); // 1 -</pre> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> Se necessitato il nome completo di un giorno (<code>"Monday"</code> per esempio ) può essere ottenuto utilizzando {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} con un parametro <code>options</code> . Utilizzando questo metodo, l'internazionalizzazione risulta più semplice:</p> - -<pre class="brush: js">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 -</pre> -</div> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.16', 'Date.prototype.getDay')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.Date.getDay")}}</p> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> - <li>{{jsxref("Date.prototype.getUTCDay()")}}</li> - <li>{{jsxref("Date.prototype.setDate()")}}</li> -</ul> 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 deleted file mode 100644 index 57d1c5efc7..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/getfullyear/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: Date.prototype.getFullYear() -slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p>Il metodo <strong><code>getFullYear()</code></strong> restituisce l'anno della data specificata in accordo con l'ora locale.</p> - -<p>Utilizza questo metodo invece di quello {{jsxref("Date.prototype.getYear()", "getYear()")}}.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getFullYear()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero corrispondente all'anno della data fornita, in accordo con l'ora locale.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il valore restituito da <code>getFullYear()</code> è un numero assoluto. Per le date tra gli anni 1000 e 9999, <code>getFullYear()</code> 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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getFullYear()">Utilizzando <code>getFullYear()</code></h3> - -<p>Il seguente esempio assegna il valore a quattro cifre dell'anno corrente alla variabile <code>year</code>.</p> - -<pre class="brush: js">var today = new Date(); -var year = today.getFullYear(); -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.3.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getFullYear")}}</p> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCFullYear()")}}</li> - <li>{{jsxref("Date.prototype.setFullYear()")}}</li> - <li>{{jsxref("Date.prototype.getYear()")}}</li> -</ul> 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 deleted file mode 100644 index 7e04a04d3f..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/gethours/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Date.prototype.getHours() -slug: Web/JavaScript/Reference/Global_Objects/Date/getHours -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getHours ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p>Il metodo <strong><code>getHours()</code></strong> restituisce l'ora per la data specificata in accordo con l'ora locale.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-gethours.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getHours()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero di tipo integer, tra 0 e 23, rappresentante l'ora per la data fornita in accordo con l'ora locale.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getHours()">Utilizzando <code>getHours()</code></h3> - -<p>La seconda dichiarazione qui sotto assegna il valore 23 alla variabile <code>hours</code>, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} <code>Xmas95</code>.</p> - -<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); -var hours = Xmas95.getHours(); - -console.log(hours); // 23 -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.18', 'Date.prototype.getHours')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getHours")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCHours()")}}</li> - <li>{{jsxref("Date.prototype.setHours()")}}</li> -</ul> 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 deleted file mode 100644 index 68825e21ca..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Date.prototype.getMilliseconds() -slug: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p>Il metodo <strong><code>getMilliseconds()</code></strong> restituisce i millisecondi nella data specificata in accordo con l'ora locale.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-getmilliseconds.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getMilliseconds()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero, tra 0 e 999, rappresentante i millisecondi per la data fornita in accordo con l'ora locale.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getMilliseconds()">Utilizzando <code>getMilliseconds()</code></h3> - -<p>Il seguente esempio assegna la porzione di millisecondi del tempo corrente alla variabile <code>milliseconds</code>:</p> - -<pre class="brush: js">var today = new Date(); -var milliseconds = today.getMilliseconds(); -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.3.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.24', 'Date.prototype.getMilliseconds')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getMilliseconds")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCMilliseconds()")}}</li> - <li>{{jsxref("Date.prototype.setMilliseconds()")}}</li> -</ul> 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 deleted file mode 100644 index 91f458cbda..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/getminutes/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Date.prototype.getMinutes() -slug: Web/JavaScript/Reference/Global_Objects/Date/getMinutes -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMinutes ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p>Il metodo <strong><code>getMinutes()</code></strong> restituisce i minuti nella data specificata in accordo con l'ora locale.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-getminutes.html")}}</div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getMinutes()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero di tipo integer, tra 0 e 59, rappresentante i minuti nella data fornita in accordo con l'ora locale.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getMinutes()">Utilizzando <code>getMinutes()</code></h3> - -<p>La seconda dichiarazione qui soto assegna il valore 15 alla variabile <code>minutes</code>, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} <code>Xmas95</code>.</p> - -<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); -var minutes = Xmas95.getMinutes(); - -console.log(minutes); // 15 -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.20', 'Date.prototype.getMinutes')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getMinutes")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCMinutes()")}}</li> - <li>{{jsxref("Date.prototype.setMinutes()")}}</li> -</ul> 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 deleted file mode 100644 index 3d954b4ed5..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/getmonth/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Date.prototype.getMonth() -slug: Web/JavaScript/Reference/Global_Objects/Date/getMonth -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMonth ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p>Il metodo <strong><code>getMonth()</code></strong> 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).</p> - -<div>{{EmbedInteractiveExample("pages/js/date-getmonth.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getMonth()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getMonth()">Utilizzando <code>getMonth()</code></h3> - -<p>La seconda dichiarazione qui sotto assegna il valore 11 alla variabile <code>month</code>, basata sul valore dell'oggetto {{jsxref("Date")}} <code>Xmas95</code>.</p> - -<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); -var month = Xmas95.getMonth(); - -console.log(month); // 11 -</pre> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> Se necessitato , il nome completo di un mese (<code>"January"</code> per esempio ) può essere ottenuto utilizzando <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat#Using_options">Intl.DateTimeFormat()</a></code> con un prametro <code>options</code> . Utilizzando questo metodo, l'internazionalizzazione risulta più semplice:</p> - -<pre class="brush: js">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 -</pre> -</div> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.12', 'Date.prototype.getMonth')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getMonth")}}</p> - -<h2 id="See_also" name="See_also">See also</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCMonth()")}}</li> - <li>{{jsxref("Date.prototype.setMonth()")}}</li> -</ul> 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 deleted file mode 100644 index 3faac2c56e..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/getseconds/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Date.prototype.getSeconds() -slug: Web/JavaScript/Reference/Global_Objects/Date/getSeconds -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getSeconds ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p>Il metodo <strong><code>getSeconds()</code></strong> restituisce i secondi nella data specificata in accordo con l'ora locale.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-getseconds.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getSeconds()</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero di tipo integer, tra 0 e 59, rappresentante i secondi nella data fonita in accordo con l'ora locale.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getSeconds()">Utilizzando <code>getSeconds()</code></h3> - -<p>La seconda dichiarazione qui sotto assegna il valore 30 alla variabile <code>seconds</code>, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} <code>Xmas95</code>.</p> - -<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); -var seconds = Xmas95.getSeconds(); - -console.log(seconds); // 30 -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.22', 'Date.prototype.getSeconds')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getSeconds")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Date.prototype.getUTCSeconds()")}}</li> - <li>{{jsxref("Date.prototype.setSeconds()")}}</li> -</ul> 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 deleted file mode 100644 index 0424faa8a4..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/gettime/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Date.prototype.getTime() -slug: Web/JavaScript/Reference/Global_Objects/Date/getTime -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTime ---- -<div> {{JSRef}}</div> - -<div> </div> - -<div>Il metodo <strong>getTime() </strong>restituisce il numero di millisecondi a partire dalla <a href="https://en.wikipedia.org/wiki/Unix_time">Unix Epoch</a>.</div> - -<p> </p> - -<p>* JavaScript utilizza i <em>millisecondi come unità di misura</em>, mentre lo Unix Time è in <em>secondi.</em></p> - -<p><em>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.</em></p> - -<p>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()")}}.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-gettime.html")}}</div> - -<p class="hidden">La sorgente di questo esempio interattivo è contenuta in una repository di GitHub. Se volessi contribuire al progetto di esempio interattivo, per favore clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> ed inviaci una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>dateObj</var>.getTime()</code></pre> - -<h3 id="Valore_di_Ritorno">Valore di Ritorno</h3> - -<p>Un numero rappresentante i millisecondi trascorsi tra il 1 Gennaio 1970 00:00:00 UTC e la data utilizzata.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzare_getTime()_per_copiare_le_date">Utilizzare <code>getTime()</code> per copiare le date</h3> - -<p>Costruire un oggetto data con lo stesso valore di tempo.</p> - -<pre class="brush: js">// 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()); -</pre> - -<h3 id="Misurare_il_tempo_di_esecuzione">Misurare il tempo di esecuzione</h3> - -<p>Sottrarre due susseguenti chiamate <code>getTime()</code> 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")}}.</p> - -<pre class="brush: js">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'); -</pre> - -<h2 id="Precisione_di_tempo_ridotta">Precisione di tempo ridotta</h2> - -<p>Per offrire protezione contro attacchi di tipo timing e fingerprinting, la precisione di <code>new Date().getTime()</code> potrebbe essere arrotondata a seconda dei settings del browser. In Firefox, la preferenza <code>privacy.reduceTimerPrecision</code> è abilitata di default e predefinita a 20µs in Firefox 59; in 60 sarà 2ms.</p> - -<pre class="brush: js">// 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 -// ... -</pre> - -<p>In Firefox, puoi anche abilitare <code>privacy.resistFingerprinting</code>, la precisione sarà 100ms oppure il valore di <code>privacy.resistFingerprinting.reduceTimerPrecision.microseconds</code>, qualunque sia superiore.</p> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazione</th> - <th scope="col">Status</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.9', 'Date.prototype.getTime')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser"> Compatibilità Browser</h2> - -<p class="hidden">La tavola di compatibilità in questa pagina è generata da dati strutturati. Se volessi contrinbuire ai dari, per favore controlla <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> ed inviaci una pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getTime")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Date.prototype.setTime()")}}</li> - <li>{{jsxref("Date.prototype.valueOf()")}}</li> - <li>{{jsxref("Date.now()")}}</li> -</ul> 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 deleted file mode 100644 index 0f583c099f..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Date.prototype.getTimezoneOffset() -slug: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset ---- -<div>{{JSRef}}</div> - -<p> </p> - -<p>Il metodo <strong><code>getTimezoneOffset()</code></strong> restituisce la differenza di fuso orario, in minuti, da corrente locale (host system settings) a UTC.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-gettimezoneoffset.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>dateObj</var>.getTimezoneOffset()</pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero rappresentante l'offset del fuso orario, in minuti, dalla data basata sul current host system settings a UTC.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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.</p> - -<table class="standard-table"> - <tbody> - <tr> - <td>Current Locale</td> - <td>UTC-8</td> - <td>UTC</td> - <td>UTC+3</td> - </tr> - <tr> - <td>Return Value</td> - <td>480</td> - <td>0</td> - <td>-180</td> - </tr> - </tbody> -</table> - -<p>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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_getTimezoneOffset()">Utilizzando <code>getTimezoneOffset()</code></h3> - -<pre class="brush: js">// 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; -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.5.26', 'Date.prototype.getTimezoneOffset')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date.getTimezoneOffset")}}</p> diff --git a/files/it/web/javascript/reference/global_objects/date/index.html b/files/it/web/javascript/reference/global_objects/date/index.html deleted file mode 100644 index 1fc4c3d9d8..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/index.html +++ /dev/null @@ -1,249 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p><span class="seoSummary">Creates a JavaScript <strong><code>Date</code></strong> instance that represents a single moment in time in a platform-independent format.</span> <code>Date</code> objects use a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16">Unix Time Stamp</a>, an integer value that is the number of milliseconds since 1 January 1970 UTC.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-constructor.html")}}</div> - - - -<h2 id="Instantiating_Date_objects">Instantiating Date objects</h2> - -<p>The only way to create a new JavaScript <code>Date</code> object is to use the {{jsxref("new")}} operator:</p> - -<pre class="brush: js">let now = new Date();</pre> - -<p>If you simply call the {{jsxref("Date", "Date()")}} object directly, the returned value is a string instead of a <code>Date</code> object. There's no <code>Date</code> literal syntax in JavaScript.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">new Date(); -new Date(<var>value</var>); -new Date(<var>dateString</var>); -new Date(<var>year</var>, <var>monthIndex</var> [, <var>day</var> [, <var>hours</var> [, <var>minutes</var> [, <var>seconds</var> [, <var>milliseconds</var>]]]]]); -</pre> - -<h3 id="Parameters">Parameters</h3> - -<p>There are four basic forms for the <code>Date()</code> constructor:</p> - -<h4 id="No_parameters">No parameters</h4> - -<p>When no parameters are provided, the newly-created <code>Date</code> object represents the current date and time, specified in the local time zone, as of the time of instantiation.</p> - -<h4 id="Unix_timestamp">Unix timestamp</h4> - -<dl> - <dt><code>value</code></dt> - <dd>A <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16">Unix Time Stamp</a> 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.</dd> -</dl> - -<h4 id="Timestamp_string">Timestamp string</h4> - -<dl> - <dt><code>dateString</code></dt> - <dd>A string value representing a date, specified in a format recognized by the {{jsxref("Date.parse()")}} method (these formats are <a href="http://tools.ietf.org/html/rfc2822#page-14">IETF-compliant RFC 2822 timestamps</a> and also strings in a <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">version of ISO8601</a>). - <div class="note"> - <p><strong>Note:</strong> parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, 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.</p> - </div> - </dd> -</dl> - -<h4 id="Individual_date_and_time_component_values">Individual date and time component values</h4> - -<p>Given at least a year and month, this form of <code>Date()</code> returns a <code>Date</code> 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 <code>day</code> and 0 for every other component).</p> - -<dl> - <dt><code>year</code></dt> - <dd>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")}}.</dd> - <dt><code>monthIndex</code></dt> - <dd>Integer value representing the month, beginning with 0 for January to 11 for December.</dd> - <dt><code>day</code> {{optional_inline}}</dt> - <dd>Integer value representing the day of the month. If not specified, the default value of 1 is used.</dd> - <dt><code>hours</code> {{optional_inline}}</dt> - <dd>Integer value representing the hour of the day. The default is 0 (midnight).</dd> - <dt><code>minutes</code> {{optional_inline}}</dt> - <dd>Integer value representing the minute segment of a time. The default is 0 minutes past the hour.</dd> - <dt><code>seconds</code> {{optional_inline}}</dt> - <dd>Integer value representing the second segment of a time. The default is zero seconds past the minute.</dd> - <dt><code>milliseconds</code> {{optional_inline}}</dt> - <dd>Integer value representing the millisecond segment of a time. The default is 0 milliseconds past the second.</dd> -</dl> - -<h2 id="User_notes">User notes</h2> - -<h3 id="The_Unix_epoch_and_timestamps">The Unix epoch and timestamps</h3> - -<p>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 <strong>Unix epoch</strong>, which is the predominant base value for computer-recorded date and time values.</p> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> 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.</p> -</div> - -<p>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 <code>Date</code> object can represent dates within ±100,000,000 (one hundred million) days relative to January 1, 1970 UTC. That means that in the year <span class="qv3Wpe" id="cwos">293,742</span>, we'll have to think about fixing this.</p> - -<h3 id="Date_format_and_time_zone_conversions">Date format and time zone conversions</h3> - -<p>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.</p> - -<p>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()")}}.</p> - -<h2 id="Properties">Properties</h2> - -<dl> - <dt>{{jsxref("Date.prototype")}}</dt> - <dd>Allows the addition of properties to a JavaScript <code>Date</code> object.</dd> - <dt><code>Date.length</code></dt> - <dd>The value of <code>Date.length</code> is 7. This is the number of arguments handled by the constructor. It's not generally a useful result.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<dl> - <dt>{{jsxref("Date.now()")}}</dt> - <dd>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.</dd> - <dt>{{jsxref("Date.parse()")}}</dt> - <dd>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. - <div class="note"> - <p><strong>Note:</strong> Parsing of strings with <code>Date.parse</code> is strongly discouraged due to browser differences and inconsistencies.</p> - </div> - </dd> - <dt>{{jsxref("Date.UTC()")}}</dt> - <dd>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.</dd> -</dl> - -<h2 id="JavaScript_Date_instances">JavaScript <code>Date</code> instances</h2> - -<p>All <code>Date</code> instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the <code>Date</code> constructor can be modified to affect all <code>Date</code> instances.</p> - -<h3 id="Date.prototype_Methods">Date.prototype Methods</h3> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}</div> - -<h2 id="Examples">Examples</h2> - -<h3 id="Several_ways_to_create_a_Date_object">Several ways to create a <code>Date</code> object</h3> - -<p>The following examples show several ways to create JavaScript dates:</p> - -<div class="note"> -<p><strong>Note:</strong> parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.</p> -</div> - -<pre class="brush: js">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); -</pre> - -<h3 id="Two_digit_years_map_to_1900_-_1999">Two digit years map to 1900 - 1999</h3> - -<p>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.</p> - -<pre class="brush: js">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) -</pre> - -<h3 id="Calculating_elapsed_time">Calculating elapsed time</h3> - -<p>The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.</p> - -<p>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.</p> - -<pre class="brush: js">// 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 -</pre> - -<pre class="brush: js">// 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 -</pre> - -<pre class="brush: js">// 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); -</pre> - -<div class="note"> -<p><strong>Note:</strong> 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()")}}.</p> -</div> - -<h3 id="Get_the_number_of_seconds_since_Unix_Epoch">Get the number of seconds since Unix Epoch</h3> - -<pre class="brush: js">var seconds = Math.floor(Date.now() / 1000); -</pre> - -<p>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()")}}).</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date-objects', 'Date')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9', 'Date')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.1.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Date", 3)}}</p> 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 deleted file mode 100644 index dcf3650fd0..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/now/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Date.now() -slug: Web/JavaScript/Reference/Global_Objects/Date/now -translation_of: Web/JavaScript/Reference/Global_Objects/Date/now ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong><code>Date.now()</code></strong> restituisce il numero di millisecondi trascori dal Gennaio 1, 1970 00:00:00 UTC.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-now.html")}}</div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>var timeInMs = Date.now();</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un {{jsxref("Number")}} rappresentante i millisecondi trascorsi fin dall'epoca UNIX.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Poichè <code>now()</code> è un metodo statico di {{jsxref("Date")}}, lo utilizzerai sempre come <code>Date.now()</code>.</p> - -<h2 id="Pecisione_di_tempo_ridotta">Pecisione di tempo ridotta</h2> - -<p>Per offrire protezione contro attacchi di tipo timing e fingerprinting, la precisione di <code>Date.now()</code> potrebbe essere arrotondata a seconda dei settings del browser.<br> - In Firefox, la preferenza di <code>privacy.reduceTimerPrecision</code> è abilitata di default e predefinita a 20ms in Firefox 59; in 60 sarà 2ms.</p> - -<pre class="brush: js">// 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 -// ... -</pre> - -<p>In Firefox, puoi anche abiliytare <code>privacy.resistFingerprinting</code>, la precisione sarà 100ms oppure il valore di <code>privacy.resistFingerprinting.reduceTimerPrecision.microseconds</code>, qualunque sia più grande.</p> - -<h2 id="Polyfill">Polyfill</h2> - -<p>Tale metodo è stato standardizzato in ECMA-262 5<sup>th</sup> edition. Motori che non sono stati aggiornati al supporto di questo metodo possono ovviare alla sua assenza utilizzando il seguente shim:</p> - -<pre class="brush: js">if (!Date.now) { - Date.now = function now() { - return new Date().getTime(); - }; -} -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.5.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.now', 'Date.now')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<p class="hidden">La tavola di compatibilità in questa pagina è generata da dati strutturati. Se volessi contribuire ai dati, per favore controlla <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> ed inviaci una pull request.</p> - -<p>{{Compat("javascript.builtins.Date.now")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{domxref("Performance.now()")}} — fornisce timestamps con risoluzione sub-millisecond per l'uso della misurazione della performance di pagine web.</li> - <li>{{domxref("console.time()")}} / {{domxref("console.timeEnd()")}}</li> -</ul> 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 deleted file mode 100644 index cfbf1abb10..0000000000 --- a/files/it/web/javascript/reference/global_objects/date/utc/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Date.UTC() -slug: Web/JavaScript/Reference/Global_Objects/Date/UTC -translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC ---- -<div>{{JSRef}}</div> - -<p><code style=""><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Il metodo </span></font><strong>Date.UTC()</strong></code> 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.</p> - -<div>{{EmbedInteractiveExample("pages/js/date-utc.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<p><strong>ECMAScript 2017 e successivi:</strong></p> - -<pre class="syntaxbox">Date.UTC(<var>year[</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minute</var>[, <var>second</var>[, <var>millisecond</var>]]]]]])</pre> - -<p><strong>ECMAScript 2016 e anteriori:</strong> <em>(utilizzo di <code>month</code> richiesto)</em></p> - -<pre class="syntaxbox">Date.UTC(<var>year</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minute</var>[, <var>second</var>[, <var>millisecond</var>]]]]])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>year</code></dt> - <dd>Un anno intero.</dd> - <dt><code>month</code></dt> - <dd>Un integer tra 0 (Gennaio) e 11 (Dicembre) rappresentante il mese. <em>(Fino a ECMAScript 2016, <code>month</code> era un parametro richiesto. Con ES2017, non lo è più.)</em></dd> - <dt><code>day</code> {{optional_inline}}</dt> - <dd>Opzionalel. Un integer tra 1 e 31 rappresentante il giorno del mese. Se omesso, è predefinito a 1.</dd> - <dt><code>hour</code> {{optional_inline}}</dt> - <dd>Un integer tra 0 e 23 rappresentante le ore. Se omesso è predefinito a 0.</dd> - <dt><code>minute</code> {{optional_inline}}</dt> - <dd>Un integer tra 0 e 59 rappresentante i minuti. Se omesso, è predefinito a 0.</dd> - <dt><code>second</code> {{optional_inline}}</dt> - <dd>Un integer tra 0 e 59 rappresentante i secondi. Se omesso, è predefinito a 0.</dd> - <dt><code>millisecond</code> {{optional_inline}}</dt> - <dd>Un integer tra 0 e 999 rappresentante i millisecondi. Se omesso, è predefinito a 0.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero rappresentante i umeri di millisecondi per la data fornita sin dal Gennaio 1, 1970, 00:00:00, UTC.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>UTC()</code> 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.</p> - -<p>Gli anni tra 0 e 99 sono convertiti ad un anno nel 20mo secolo<code>(1900 + year)</code>; per esempio, 95 è convertito all'anno 1995.</p> - -<p>Il metodo <code>UTC()</code> differisce dal costruttore {{jsxref("Date")}} in due modi.</p> - -<ul> - <li><code>Date.UTC()</code> utilizza il tempo universale invece di quello locale.</li> - <li><code>Date.UTC()</code> restituisce un valore di tempo come numero invece di creare un oggetto {{jsxref("Date")}}.</li> -</ul> - -<p>Se un parametro è fuori dal range previsto, il metodo <code>UTC()</code> aggiorna gli altri parametri per adattare il valore. Per esempio, se 15 è usato per il mese, l'anno sarà incrementato di 1 <code>(year + 1)</code> e 3 sarà usato per il mese.</p> - -<p><code>UTC()</code> è un metodo statico di {{jsxref("Date")}}, per questo è chiamato come <code>Date.UTC()</code> invece che come un metodo di istanza {{jsxref("Date")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_Date.UTC()">Utilizzando <code>Date.UTC()</code></h3> - -<p>La seguente dichiarazione crea un oggetto {{jsxref("Date")}} con gli argomenti trattati come UTC invece di local:</p> - -<pre class="brush:js">var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0)); -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td> Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.Date.UTC")}}</p> - -<h2 id="Note_di_compatibilità">Note di compatibilità</h2> - -<h3 id="Date.UTC_con_meno_di_due_argomenti"><code>Date.UTC</code> con meno di due argomenti</h3> - -<p>Quando si provvedono meno di due argomenti a <code>Date.UTC</code>, ECMAScript 2017 richiede che {{jsxref("NaN")}} sia restituito. Motori che non supportavano tale comportamento sono stati aggiornati (vedere {{bug(1050755)}}, <a href="https://github.com/tc39/ecma262/pull/642">ecma-262 #642</a>).</p> - -<pre class="brush: js">Date.UTC(); -Date.UTC(1); - -// Safari: NaN -// Chrome/Opera/V8: NaN - -// Firefox <54: non-NaN -// Firefox 54+: NaN - -// IE: non-NaN -// Edge: NaN -</pre> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Date.parse()")}}</li> - <li>{{jsxref("Date")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/decodeuri/index.html b/files/it/web/javascript/reference/global_objects/decodeuri/index.html deleted file mode 100644 index 40a65b0c57..0000000000 --- a/files/it/web/javascript/reference/global_objects/decodeuri/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: decodeURI() -slug: Web/JavaScript/Reference/Global_Objects/decodeURI -translation_of: Web/JavaScript/Reference/Global_Objects/decodeURI ---- -<div>{{jsSidebar("Objects")}}</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>decodeURI()</code></strong> decodifica un {{Glossary("URI")}} creato da {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} o una funzione simile.</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>decodeURI(<i>encodedURI</i>)</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>encodedURI</code></dt> - <dd>Un {{Glossary("URI")}} completo.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>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 <code><strong>#</strong></code>.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Decodificare_un_URL_in_Cirillico">Decodificare un URL in Cirillico</h3> - -<pre class="brush: js">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_шеллы" -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>ECMAScript 3rd Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.3.1', 'decodeURI')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-decodeuri-encodeduri', 'decodeURI')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> - <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html b/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html deleted file mode 100644 index 243bd14a93..0000000000 --- a/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: decodeURIComponent() -slug: Web/JavaScript/Reference/Global_Objects/decodeURIComponent -translation_of: Web/JavaScript/Reference/Global_Objects/decodeURIComponent ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>decodeURIComponent()</code></strong> decodifica una parte di {{Glossary("URI")}} creata da {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}} o una funzione simile.</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>decodeURIComponent(<em>encodedURIComponent</em>)</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>encodedURIComponent</code></dt> - <dd>Una parte codificata di un {{Glossary("URI")}}</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>Sostituisce ogni sequenza di escape nella parte di {{Glossary("URI")}} codificata con il carattere che la rappresenta.</p> - -<h2 id="Esempio">Esempio</h2> - -<h3 id="Decodificare_una_parte_di_URL_in_Cirillico">Decodificare una parte di URL in Cirillico</h3> - -<pre class="brush: js">decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"); -// "JavaScript_шеллы" -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 3rd Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.3.2', 'decodeURIComponent')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-decodeuricomponent-encodeduricomponent', 'decodeURIComponent')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_Also" name="See_Also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/encodeuri/index.html b/files/it/web/javascript/reference/global_objects/encodeuri/index.html deleted file mode 100644 index 24118aec60..0000000000 --- a/files/it/web/javascript/reference/global_objects/encodeuri/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: encodeURI() -slug: Web/JavaScript/Reference/Global_Objects/encodeURI -translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>encodeURI()</code></strong> 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").</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>encodeURI(<em>uri</em>)</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code><font face="Consolas, Monaco, Andale Mono, monospace">uri</font></code></dt> - <dd>Un {{Glossary("URI")}} completo.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>Questa funzione assume che <code>uri</code> sia un {{Glossary("URI")}} completo, quindi non codifica i caratteri riservati che hanno un significato particolare nell'{{Glossary("URI")}}.</p> - -<p><code>encodeURI</code> sostituisce tutti i caratteri con la sequenza di escape UTF-8 appropriata, ecceto i seguenti:</p> - -<table class="standard-table"> - <tbody> - <tr> - <td class="header">Tipo</td> - <td class="header">Caratteri</td> - </tr> - <tr> - <td>Caratteri riservati</td> - <td><code>;</code> <code>,</code> <code>/</code> <code>?</code> <code>:</code> <code>@</code> <code>&</code> <code>=</code> <code>+</code> <code>$</code></td> - </tr> - <tr> - <td>Caratteri non codificati</td> - <td>lettere, cifre, <code>-</code> <code>_</code> <code>.</code> <code>!</code> <code>~</code> <code>*</code> <code>'</code> <code>(</code> <code>)</code></td> - </tr> - <tr> - <td>Score</td> - <td><code>#</code></td> - </tr> - </tbody> -</table> - -<p><code>encodeURI</code> <strong>non</strong> 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()")}}.</p> - -<p>Se si tenta di codificare un surrogato che non è parte di una coppia, verrà generato un {{jsxref("Global_Objects/URIError", "URIError")}}.</p> - -<pre class="brush: js">// 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"); </pre> - -<p>Se uno desidera seguire il più recente standard per gli {{Glossary("URL")}} <a href="http://tools.ietf.org/html/rfc3986">RFC3986</a>, nel quale le parentesi quadre sono caratteri riservati (per gli indirizzi {{Glossary("IPv6")}}), può essere utile il seguente codice:</p> - -<pre class="brush: js">function fixedEncodeURI(str) { - return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); -}</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 3rd Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.3.3', 'encodeURI')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-encodeuri-uri', 'encodeURI')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_Also" name="See_Also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> - <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html deleted file mode 100644 index 66b290ccb4..0000000000 --- a/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: encodeURIComponent() -slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent -translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent ---- -<div>{{jsSidebar("Objects")}}</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>encodeURIComponent()</code></strong> 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").</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox">encodeURIComponent(uriComponent);</pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>uriComponent</code></dt> - <dd>Una parte di un {{Glossary("URI")}}</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p><code>encodeURIComponent</code> sostituisce tutti i caratteri esclusi i seguenti: lettere, cifre, <code>- _ . ! ~ * ' ( )</code></p> - -<p>Se si tenta di codificare un surrogato che non è parte di una coppia, verrà generato un {{jsxref("Global_Objects/URIError", "URIError")}}.</p> - -<pre class="brush: js">// 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");</pre> - -<p>Per evitare problemi inaspettati durante le richieste al server, bisognerebbe richiamare <code>encodeURIComponent</code> su ogni dato inserito dall'utente che verrà passato come parte di un {{Glossary("URI")}}. Per esempio, un un utente potrebbe digitare "<code>Cani&Gatti = animali"</code>. Senza utilizzare la funzione <code>encodeURIComponent</code>, la richiesta verrebbe costruita in modo simile a "<code>commento=Cani&Gatti%20=%20animali</code>". Notare che sono due variabili separate: "<code>commento</code>" e "<code>Gatti%20</code>". Utilizzando quuesta funzione verrebbe invece costruita come "<code>commento=Cani%26Gatti%20%3D%20animali</code>".</p> - -<p>Utilizzando <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#application/x-www-form-urlencoded-encoding-algorithm"><code>application/x-www-form-urlencoded</code></a>, gli spazi devono essere sostituiti da un "<code>+</code>"., quindi si potrebbe usare la funzione <code>encodeURIComponent</code> seguita da un altra sostituzione da "<code>%20</code>" a "<code>+</code>".</p> - -<p>Per aderire con più precisione allo standard <a class="external" href="http://tools.ietf.org/html/rfc3986">RFC 3986</a> (secondo il quale <code>!</code>, <code>'</code>, <code>(</code>, <code>)</code> e <code>*</code> sono caratteri riservati), si può usare la seguente funzione:</p> - -<pre class="brush: js">function fixedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return '%' + c.charCodeAt(0).toString(16); - }); -} -</pre> - -<h2 id="See_also" name="See_also">Esempi</h2> - -<p>Il seguente esempio fornisce un metodo per codificare come richiesto dall'header <code>Content-Disposition</code>:</p> - -<pre class="brush: js">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); -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 3rd Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> - <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/escape/index.html b/files/it/web/javascript/reference/global_objects/escape/index.html deleted file mode 100644 index 77fa1e5bf0..0000000000 --- a/files/it/web/javascript/reference/global_objects/escape/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: escape() -slug: Web/JavaScript/Reference/Global_Objects/escape -translation_of: Web/JavaScript/Reference/Global_Objects/escape ---- -<div> -<div> -<div>{{jsSidebar("Objects")}} {{deprecated_header}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>escape()</code></strong>, 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()")}}.</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>escape(string)</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>string</code></dt> - <dd>La stringa da codificare.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>La funzione <code>escape()</code> è una proprietà dell'<em>oggetto globale</em>. Vengono codificati tutti i caratteri speciali, ad eccezione di: <code>@ * _ + - . /</code></p> - -<p>I caratteri vengono sostituiti con codici esadecimali che possono avere due caratteri, se il loro valore è minore o ugugale a 0xFF, (%xx) oppure quattro (%<strong>u</strong>xxxx).</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">escape("abc123"); // "abc123" -escape("äöü"); // "%E4%F6%FC" -escape("ć"); // "%u0107" - -// Caratteri speciali -escape("@*_+-./"); // "@*_+-./"</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-B.2.1', 'escape')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definita nell'appendice B, "<em>Compatibility</em>"</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-escape-string', 'escape')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Definita nell'appendice B, "<em>Additional ECMAScript Features for Web Browsers</em>"</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_Also" name="See_Also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/eval/index.html b/files/it/web/javascript/reference/global_objects/eval/index.html deleted file mode 100644 index 22e3c70bb6..0000000000 --- a/files/it/web/javascript/reference/global_objects/eval/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: eval() -slug: Web/JavaScript/Reference/Global_Objects/eval -translation_of: Web/JavaScript/Reference/Global_Objects/eval ---- -<p>{{jsSidebar("Objects")}}</p> - -<h2 id="Summary" name="Summary">Riassunto</h2> - -<p>Il metodo <code><strong>eval()</strong></code> esegue il codice JavaScript rappresentato come una stringa.</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>eval(<em>stringa</em>)</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>string</code></dt> - <dd>Una stringa che rappresenta un'espressione JavaScript, dichiarazione o sequenza di istruzioni. L'espressione può includere le variabili e le proprietà degli oggetti esistenti.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p><code>eval()</code> è una funzione dell'oggetto globale.</p> - -<p>L'argomento della funzione <code>eval()</code> è una stringa. Se la stringa rappresenta un'espressione, <code>eval()</code> esegue l'espressione. Se l'argomento rappresenta una o più dichiarazioni Javascript, <code>eval()</code>esegue le dichiarazioni. Non chiamare <code>eval()</code> per eseguire un'operazione aritmetica, JavaScript la esegue automaticamente.</p> - -<p>Se si costruisce un'espressione aritmetica come una stringa, è possibile usare <code>eval()</code> per eseguirla in un secondo momento. Ad esempio, supponiamo di avere una variabile <code>x</code>. E' possibile rinviare il valore di un'espressione che coinvolge <code>x</code> assegnando il valore della stringa dell'espressione, tipo "<code>3 * x + 2</code>", ad una variabile, e quindi chiamare <code>eval()</code> in un punto successivo dello script.</p> - -<p>Se l'argomento di <code>eval()</code> non è una stringa, <code>eval()</code> restituisce l'argomento immutato. Nell'esempio qui sotto, il costrutto <code>String</code> viene specificato, e <code>eval()</code> ritorna un oggetto <code>String</code> piuttosto che il risultato della stringa.</p> - -<pre class="brush:js">eval(new String("2 + 2")); // returns a String object containing "2 + 2" -eval("2 + 2"); // returns 4 -</pre> - -<p>E' possibile aggirare questa limitazione in modo generico utilizzando <code>toString()</code>.</p> - -<pre class="brush:js">var expression = new String("2 + 2"); -eval(expression.toString()); -</pre> - -<p>Non è possibile utilizzare la funzione <code>eval</code> indirettamente, invocandola con un nome diverso da <code>eval()</code>; se lo fai , potrebbe verificarsi un errore di sintassi. Per esempio, non si dovrebbe usare il seguente codice:</p> - -<pre class="brush:js">var x = 2; -var y = 4; -var myEval = eval; -myEval("x + y"); -</pre> - -<h2 id="Don.27t_use_eval.21" name="Don.27t_use_eval.21"><a name="dont-use-it">Non usate eval inutilmente!</a></h2> - -<p><code>eval()</code>è una funzione pericolosa, che esegue il codice con i privilegi dell'amministratore della pagina. Se si esegue <code>eval()</code> 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 <code>eval()</code> è stata invocata, che può portare a possibili attacchi come {{jsxref("Global_Objects/Function", "Function")}}.</p> - -<p><code>eval()</code> è 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.</p> - -<p>Queste sono alternative più sicure (e veloci! ) ad <code>eval()</code> per comuni impieghi.</p> - -<h3 id="Accessing_member_properties" name="Accessing_member_properties">Accesso alle proprietà utente</h3> - -<p>Si consiglia si non utilizzare <code>eval()</code> 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:</p> - -<pre class="brush:js">var obj = { a: 20, b: 30 }; -var propname = getPropName(); //returns "a" or "b" - -eval( "var result = obj." + propname ); -</pre> - -<p>Tuttavia, <code>eval ()</code> non è necessario qui. In realtà, il suo uso è sconsigliato qui. Invece, utilizzare gli <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators" title="JavaScript/Reference/Operators/Member_Operators">operatori membri</a>, che sono molto più veloci e sicuri:</p> - -<pre class="brush:js">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 -</pre> - -<h3 id="Use_functions_instead_of_evaluating_snippets_of_code" name="Use_functions_instead_of_evaluating_snippets_of_code">Utilizzare le funzioni invece di eseguire frammenti di codice</h3> - -<p>JavaScript ha <a class="external" href="http://en.wikipedia.org/wiki/First-class_function" title="http://en.wikipedia.org/wiki/First-class_function">funzioni di prima classe</a>, 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:</p> - -<pre class="brush: js">// instead of setTimeout(" ... ", 1000) use: -setTimeout(function() { ... }, 1000); - -// instead of elt.setAttribute("onclick", "...") use: -elt.addEventListener("click", function() { ... } , false); </pre> - -<p><a href="/en-US/docs/Web/JavaScript/Guide/Closures" title="JavaScript/Guide/Closures">Le chiusure</a> sono utili anche come un modo per creare funzioni parametrizzate senza concatenazioni di stringhe.</p> - -<h3 id="Parsing_JSON_(converting_strings_to_JavaScript_objects)" name="Parsing_JSON_(converting_strings_to_JavaScript_objects)">Analisi di JSON (conversione di stringhe in oggetti JavaScript)</h3> - -<p>Se la stringa che si sta chiamando <code>eval()</code> contiene dati (per esempio un array: <code>"[1, 2, 3]"</code>), al ontrario del codice, si dovrebbe considerareil passaggio a <a href="/en-US/docs/JSON" title="JSON">JSON</a>, che permette la stringa di utilizzre un sottoinsieme della sintassi Javascript per rappresentare i dati. Vedi anche <a href="/en-US/docs/Downloading_JSON_and_JavaScript_in_extensions" title="Downloading_JSON_and_JavaScript_in_extensions">Downloading JSON and JavaScript in extensions</a>.</p> - -<p>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.</p> - -<h3 id="Pass_data_instead_of_code" name="Pass_data_instead_of_code">Paasare i dati al posto di codici</h3> - -<p>Ad esempio, un'estensione progettata per raschiare contenuti delle pagine Web potrebbe avere le regole di raschiatura definite in <a href="/en-US/docs/XPath" title="XPath">XPath</a> invece di codice Javascript.</p> - -<h3 id="Run_code_with_limited_privileges" name="Run_code_with_limited_privileges">Eseguire codice con privilegi limitati</h3> - -<p>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 <a href="/en-US/docs/Components.utils.evalInSandbox" title="Components.utils.evalInSandbox">Components.utils.evalInSandbox</a> per questo.</p> - -<h2 id="Examples" name="Examples">Esempio</h2> - -<p>Il seguente esempio mostra output utilizzando <a href="/en-US/docs/Web/API/document.write"><code>document.write</code></a>. Nel server-side JavaScript, è possibile visualizzare la stessa uscita chiamando la funzione <code>write()</code> invece di utilizzare il <code>document.write()</code>.</p> - -<h3 id="Example:_Using_eval" name="Example:_Using_eval">Esempio: Usare <code>eval</code></h3> - -<p>Nel codice seguente, entrambe le dichiarazioni contenenti <code>eval()</code> restituiscono 42. La prima restituisce la stringa "<code>x + y + 1</code>" ; la seconda esegue la stringa "<code>42</code>".</p> - -<pre class="brush:js">var x = 2; -var y = 39; -var z = "42"; -eval("x + y + 1"); // returns 42 -eval(z); // returns 42 -</pre> - -<h3 id="Example:_Using_eval_to_evaluate_a_string_of_JavaScript_statements" name="Example:_Using_eval_to_evaluate_a_string_of_JavaScript_statements">Esempio: Usare <code>eval</code> Per eseguire una serie di istruzioni JavaScript.</h3> - -<p>Il seguente esempio utilizza <code>eval()</code> per eseguire la stringa <code>str</code>. Questa stringa consiste in una serie di istruzioni JavaScript che aprono una finestra di avviso e assegnano a <code>z</code> un valore 42 se <code>x</code> è di cinque, e assegna 0 a <code>z</code> altrimenti. Quando viene eseguita la seconda istruzione, <code>eval()</code> farà si che questa dichiarazioni da effettuare, e sarà anche eseguire l'insieme di istruzioni e restituire il valore che viene assegnato a <code>z</code>.</p> - -<pre class="brush:js">var x = 5; -var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; "; - -document.write("<P>z is ", eval(str));</pre> - -<h3 id="Return_value" name="Return_value">Esempio: L'ultima espressione viene eseguita</h3> - -<p><code>eval()</code>restituisce il valore dell'ultima espressione valutata.</p> - -<pre class="brush:js">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);</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.2.1', 'eval')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-eval-x', 'eval')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome per Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h3 id="See_Also" name="See_Also">Gecko-specific notes</h3> - -<ul> - <li>Storicamente <code>eval()</code> ha avuto un secondo argomento opzionale, specificando un oggetto nel cui contesto la valutazione doveva essere eseguita. Questo argomento è stato non-standard, ed è stato rimosso dal SpiderMonkey in Gecko 1.9.1 (Firefox 3.5). Vedere {{ bug(442333) }}.</li> -</ul> - -<h2 id="See_Also" name="See_Also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/uneval", "uneval()")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators">Member operators</a></li> -</ul> 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 deleted file mode 100644 index 1c0d04272d..0000000000 --- a/files/it/web/javascript/reference/global_objects/function/apply/index.html +++ /dev/null @@ -1,250 +0,0 @@ ---- -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 ---- -<div> -<p>{{JSRef}}</p> - -<p>Il metodo <code><strong>apply()</strong></code> chiama una funzione passandole il "<code>this</code>" ed i parametri forniti sottoforma di array (o <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array-like object</a>).</p> - -<p><strong>Nota:</strong> Mentre la sintassi di questa funzione è quasi completamente identica a quella di {{jsxref("Function.call", "call()")}}, la fondamentale differenza è che <code>call()</code> accetta una <strong>lista di parametri</strong>, mentre <code>apply()</code> accetta un <strong>singolo array contenente una lista di parametri</strong>.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre><code><var>fun</var>.apply(<var>thisArg, </var>[<var>argsArray</var>])</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>thisArg</code></dt> - <dd>Il valore del <code>this</code> da fornire alla chiamata a <em><code>fun</code></em>. 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.</dd> - <dt><code>argsArray</code></dt> - <dd>Un array-like object che specifica i parametri con la quale la funzione <em><code>fun</code></em> 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")}}.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>this</code> solitamente si riferisce all'oggetto corrente, ma grazie ad <code>apply</code> è 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.</p> - -<p><code>apply</code> è 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 <code>apply</code>, ad esempio, puoi utilizzare il seguente array literal: <code><em>fun</em>.apply(this, ['eat', 'bananas'])</code>, o il seguente oggetto {{jsxref("Array")}}: <code><em>fun</em>.apply(this, new Array('eat', 'bananas'))</code>.</p> - -<p>Puoi anche utilizzare {{jsxref("Functions/arguments", "arguments")}} per il parametro <code>argsArray<font face="Open Sans, Arial, sans-serif">. </font></code><code>arguments</code> è 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.</p> - -<p>Da ECMAScript 5 puoi anche usare qualunque tipo di array-like object. Ad esempio puoi utilizzare un {{domxref("NodeList")}} o un oggetto come <code>{ 'length': 2, '0': 'eat', '1': 'bananas' }</code>.</p> - -<p>{{note("La maggior parte dei browser, incluso Chrome 14 ed Internet Explorer 9, non accetto array-like objects e lanceranno una eccezione.")}}</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzare_apply_per_concatenare_costruttori">Utilizzare apply per concatenare costruttori</h3> - -<p>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 <code>construct</code>, che ti permetterà di utilizzare un array-like object con un costruttore anziché una lista di argomenti.</p> - -<pre>Function.prototype.construct = function (aArgs) { - var oNew = Object.create(this.prototype); - this.apply(oNew, aArgs); - return oNew; -}; -</pre> - -<p><strong>Note:</strong> Il metodo <code>Object.create()</code> usato nell'esempio sovrastante è relativamente nuovo. Per un alternativa che utilizza le closures considera questo pezzo di codice:</p> - -<pre>Function.prototype.construct = function(aArgs) { - var fConstructor = this, fNewConstr = function() { - fConstructor.apply(this, aArgs); - }; - fNewConstr.prototype = fConstructor.prototype; - return new fNewConstr(); -};</pre> - -<p>Esempio d'uso:</p> - -<pre>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' -</pre> - -<p><strong>Note:</strong> Il metodo non nativo <code>Function.construct</code> 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")}}: <code>[2012, 11, 4]</code>; In questo caso dovresti scrivere qualcosa come: <code>new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))()</code> — ad ogni modo questo non è il miglior modo di fare le cose e non andrebbe mai usato in produzione.</p> - -<h3 id="Utilizzare_apply_combinato_alle_funzioni_built-in">Utilizzare apply combinato alle funzioni built-in</h3> - -<p>Un intelligente uso di <code>apply</code> 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 <code>Math.max</code>/<code>Math.min</code>.</p> - -<pre>// 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]; - } -} -</pre> - -<p>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.<br> - Le conseguenze nel fare ciò variano da motore a motore (ad esempio JavaScriptCore ha il limite settato a mano di <a href="https://bugs.webkit.org/show_bug.cgi?id=80797">65536</a> 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 <em><code>apply().</code></em> (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 <code>5, 6, 2, 3</code>, 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:</p> - -<pre>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]); -</pre> - -<h3 id="Usare_apply_come_monkey-patch">Usare apply come "monkey-patch"</h3> - -<p>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 <code>someobject.foo</code>, è possibile modificarne il funzionamento in questo modo:</p> - -<pre>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. -} -</pre> - -<p>Questo metodo ritorna particolarmente utile quando vuoi debuggare eventi e interfacce con qualcosa che non espone API come i diversi eventi <code>.on([event]...</code> (usabili anche dal <a href="/en-US/docs/Tools/Page_Inspector#Developer_API">Devtools Inspector</a>).</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.3.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser</h2> - -<p>{{CompatibilityTable}}</p> - -<table> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - <tr> - <td>ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoDesktop("2.0")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> - -<table> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - <tr> - <td>ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("2.0")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Functions/arguments", "arguments")}} object</li> - <li>{{jsxref("Function.prototype.bind()")}}</li> - <li>{{jsxref("Function.prototype.call()")}}</li> - <li>{{jsxref("Functions", "Functions and function scope", "", 1)}}</li> - <li>{{jsxref("Reflect.apply()")}}</li> -</ul> -</div> 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 deleted file mode 100644 index 949e5f9cdb..0000000000 --- a/files/it/web/javascript/reference/global_objects/function/arguments/index.html +++ /dev/null @@ -1,92 +0,0 @@ ---- -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 ---- -<div>{{JSRef}} {{deprecated_header}}</div> - -<p>La proprieta' <code><strong><em>function</em>.arguments</strong></code> 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.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">La sintassi </span></font><em>function</em>.arguments</code> 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")}}.</p> - -<p>In caso di ricorsione, per esempio, se la funzione <code>f</code> e' presente diverse volte nello stack, il valore di <code>f.arguments</code> rappresenta i parametri corrispondenti alla chiamata alla funzione piu' recente.</p> - -<p>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).</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0. Deprecated in favor of {{jsxref("Functions/arguments", "arguments")}} in ES3.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>{{jsxref("Functions/arguments", "arguments")}} object</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>{{jsxref("Functions/arguments", "arguments")}} object</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td>{{jsxref("Functions/arguments", "arguments")}} object</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilita_Browser">Compatibilita' Browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Function.arguments")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Functions/arguments", "arguments")}} object</li> - <li>{{jsxref("Functions", "Functions and function scope", "", 1)}}</li> -</ul> 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 deleted file mode 100644 index 38187ac5e6..0000000000 --- a/files/it/web/javascript/reference/global_objects/function/bind/index.html +++ /dev/null @@ -1,277 +0,0 @@ ---- -title: Function.prototype.bind() -slug: Web/JavaScript/Reference/Global_Objects/Function/bind -translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>bind()</strong></code> crea una nuova funzione che, quando chiamata, ha parola chiave <strong><code>this</code></strong> impostata sul valore fornito, con una data sequenza di argomenti che precede quella fornita quando viene chiamata la nuova funzione</p> - -<p>{{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}}</p> - -<p class="hidden">La fonte per questo esempio interattivo è memorizzata in un repository GitHub. Se desideri contribuire al progetto di esempi interattivi, ti preghiamo di clonare. <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviarci una richiesta di pull.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>function</var></code>.bind(<var>thisArg</var>[, <var>arg1</var>[, <var>arg2</var>[, ...]]])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>thisArg</code></dt> - <dd>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 <code>bind</code> per creare una funzione (fornita come callback) all'interno di un setTimeout, qualsiasi valore primitivo passato come <code>thisArg</code> viene convertito in oggetto. Se non vengono forniti argomenti per vincolarlo, l'esecuzione viene considerata come <code>thisArg</code> per la nuova funzione.</dd> - <dt><code>arg1, arg2, ...</code></dt> - <dd>Argomenti da anteporre agli argomenti forniti alla funzione associata quando si richiama la funzione di destinazione.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Una copia della funzione data con specificato <strong><code>this</code></strong> valore e gli argomenti iniziali.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>La funzione <code>bind()</code> crea una nuova <strong>funzione associata</strong> <strong>(BF, bound function)</strong>. Un BF è un <em>exotic function object </em>(oggetto funzione esotico, un termine di ECMAScript 2015) che racchiude l'oggetto funzione originale. Chiamare un BF generalmente comporta l'esecuzione della sua funzione <em>wrapped</em> (avvolta).<br> - Un BF ha le seguenti proprietà interne:</p> - -<ul> - <li><strong>[[BoundTargetFunction]]</strong> - l'oggetto funzione avvolto;</li> - <li><strong>[[BoundThis]]</strong> - il valore che viene sempre passato come questo valore quando si chiama la funzione wrapped.</li> - <li><strong>[[BoundArguments]] - </strong>un elenco di valori i cui elementi vengono utilizzati come primi argomenti per qualsiasi chiamata alla funzione wrapped.</li> - <li><strong>[[Call]]</strong> - esegue il codice associato a questo oggetto. Invocato tramite un'espressione di chiamata di funzione. Gli argomenti del metodo interno sono un valore e un elenco contenente gli argomenti passati alla funzione da un'espressione di chiamata.</li> -</ul> - -<p>Quando viene chiamata la funzione associata, chiama il metodo interno <strong>[[Call]]</strong> su<strong> [[BoundTargetFunction]]</strong>, con i seguenti argomenti <code>call(boundThis, ...args)</code>. Dove, <code>boundThis</code> è <strong>[[BoundThis]]</strong>, <code>args</code> è <strong>[[BoundArguments]] </strong>seguito dagli argomenti passati dalla chiamata alla funzione.</p> - -<p>Una funzione associata (bound function) può anche essere costruita usando l'operatore <a href="/it/docs/Web/JavaScript/Reference/Operators/new">new</a>: agendo in tal modo si comporta come se la funzione obiettivo fosse stata invece costruita. Il valore <code>this</code> fornito viene ignorato, mentre gli argomenti preposti sono forniti alla funzione emulata.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Creare_una_funzione_associata">Creare una funzione associata</h3> - -<p>L'uso più semplice di <code>bind()</code> è 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:</p> - -<pre class="brush: js">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 <code>var boundGetX = retrieveX.bind(module);</code> -boundGetX(); // 81 -</pre> - -<h3 id="Funzioni_parzialmente_applicate">Funzioni parzialmente applicate</h3> - -<p>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.</p> - -<pre class="brush: js">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] -</pre> - -<h3 id="Con_setTimeout">Con <code>setTimeout</code></h3> - -<p>Di default all'interno di {{domxref("window.setTimeout()")}}, la parola chiave <code>this</code> verrà impostata sull'oggetto {{ domxref("window") }} (or <code>global</code>). Quando si lavora con metodi di classe che richiedono questo <code>this</code> riferimento alle istanze di classe, è possibile associarlo esplicitamente alla funzione di callback, al fine di mantenere l'istanza.</p> - -<pre class="brush: js">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'</pre> - -<h3 id="Funzioni_associate_utilizzate_come_costruttori">Funzioni associate utilizzate come costruttori</h3> - -<div class="warning"> -<p><strong>Warning:</strong> 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.</p> -</div> - -<p>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:</p> - -<pre class="brush: js">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 -</pre> - -<p>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")}}.</p> - -<pre class="brush: js">// 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' -</pre> - -<p>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.</p> - -<h3 id="Creating_shortcuts">Creating shortcuts</h3> - -<p><code>bind()</code> is also helpful in cases where you want to create a shortcut to a function which requires a specific <strong><code>this</code></strong> value.</p> - -<p>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:</p> - -<pre class="brush: js">var slice = Array.prototype.slice; - -// ... - -slice.apply(arguments); -</pre> - -<p>With <code>bind()</code>, this can be simplified. In the following piece of code, <code>slice</code> is a bound function to the {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the <strong><code>this</code></strong> value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional <code>apply()</code> calls can be eliminated:</p> - -<pre class="brush: js">// same as "slice" in the previous example -var unboundSlice = Array.prototype.slice; -var slice = Function.prototype.apply.bind(unboundSlice); - -// ... - -slice(arguments); -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>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 <code>bind()</code> in implementations that do not natively support it.</p> - -<pre class="brush: js">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; - }; -} -</pre> - -<p>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:</p> - -<ul> - <li>The partial implementation relies on {{jsxref("Array.prototype.slice()")}}, {{jsxref("Array.prototype.concat()")}}, {{jsxref("Function.prototype.call()")}} and {{jsxref("Function.prototype.apply()")}}, built-in methods to have their original values.</li> - <li>The partial implementation creates functions that do not have immutable "poison pill" {{jsxref("Function.caller", "caller")}} and <code>arguments</code> properties that throw a {{jsxref("Global_Objects/TypeError", "TypeError")}} upon get, set, or deletion. (This could be added if the implementation supports {{jsxref("Object.defineProperty")}}, or partially implemented [without throw-on-delete behavior] if the implementation supports the {{jsxref("Object.defineGetter", "__defineGetter__")}} and {{jsxref("Object.defineSetter", "__defineSetter__")}} extensions.)</li> - <li>The partial implementation creates functions that have a <code>prototype</code> property. (Proper bound functions have none.)</li> - <li>The partial implementation creates bound functions whose {{jsxref("Function.length", "length")}} property does not agree with that mandated by ECMA-262: it creates functions with length 0, while a full implementation, depending on the length of the target function and the number of pre-specified arguments, may return a non-zero length.</li> -</ul> - -<p>If you choose to use this partial implementation, <strong>you must not rely on those cases where behavior deviates from ECMA-262, 5th edition!</strong> 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 <code>bind()</code> is widely implemented according to the specification.</p> - -<p>Please check <a href="https://github.com/Raynos/function-bind">https://github.com/Raynos/function-bind</a> for a more thorough solution!</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.8.5.</td> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Function.bind")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Function.prototype.apply()")}}</li> - <li>{{jsxref("Function.prototype.call()")}}</li> - <li>{{jsxref("Functions", "Functions", "", 1)}}</li> -</ul> 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 deleted file mode 100644 index 54acd401ca..0000000000 --- a/files/it/web/javascript/reference/global_objects/function/call/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Function.prototype.call() -slug: Web/JavaScript/Reference/Global_Objects/Function/call -translation_of: Web/JavaScript/Reference/Global_Objects/Function/call ---- -<div>{{JSRef}}</div> - -<p><span class="seoSummary">Il metodo <code><strong>call()</strong></code> esegue una funzione con un dato valore <code>this</code> e argomenti passati singolarmente.</span></p> - -<div class="note"> -<p><strong>Note:</strong> Mentre la sintassi di questa funzione è quasi identica a quella di {{jsxref("Function.prototype.apply", "apply()")}}, la differenza fondamentale è che <code>call()</code> accetta una <strong>lista di argomenti</strong> mentre <code>apply()</code> accetta un <strong>singolo array di argomenti</strong>.</p> -</div> - -<div>{{EmbedInteractiveExample("pages/js/function-call.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>func</var>.call([<var>thisArg</var>[, <var>arg1</var>, <var>arg2</var>, ...<var>argN</var>]])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code><var>thisArg</var></code> {{optional_inline}}</dt> - <dd> - <p>Il valore da usare come <code>this</code> quando si esegue <code><var>func</var></code>.</p> - - <div class="blockIndicator note"> - <p><strong>Attenzione:</strong> In certi casi, <code><var>thisArg</var></code> potrebbe non essere il valore reale visto dal metodo.</p> - - <p>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.</p> - </div> - </dd> - <dt><code><var>arg1</var>, <var>arg2</var>, ...<var>argN</var></code> {{optional_inline}}</dt> - <dd>Argomenti per la funzione.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Il risultato dell'esecuzione della funzione con il <code><strong>this</strong></code> e gli argomenti specificati.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>call()</code> consente a una funzione/metodo appartenente a un oggetto di essere essere assegnata e chiamata per un oggetto diverso..</p> - -<p><code>call()</code> fornisce un nuova valore di <code>this</code> alla funzione/metodo. Con <code>call()</code>, si può scrivere un metodo una volta ed ereditarlo in un altro oggetto senza dover riscrivere il metodo per il nuovo oggetto.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_call_per_collegare_costruttori_per_un_oggetto">Usare <code>call</code> per collegare costruttori per un oggetto</h3> - -<p>Si può usare <code>call</code> per collegare costruttori per un oggetto (simile a Java).</p> - -<p>Nell'esempio seguente, il costruttore per l'oggetto <code>Product</code> è definito con 2 parametri: <code>name</code> e <code>price</code>.</p> - -<p>Due altre funzioni, <code>Food</code> e <code>Toy</code>, invocano <code>Product</code>, passando <code>this</code>, <code>name</code>, e <code>price</code>. <code>Product</code> inizializza le proprietà <code>name</code> e <code>price</code>. Entrambe le funzioni specializzate definiscono la <code>category</code>.</p> - -<pre class="brush: js">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); -</pre> - -<h3 id="Usare_call_per_invocare_una_funzione_anonima">Usare <code>call</code> per invocare una funzione anonima</h3> - -<p>In questo esempio, viene create una funzione anonima e usato <code>call</code> per invocarla su ogni oggetto di un array.</p> - -<p>Lo scopo principale della funzione anonima qui è di aggiungere una funzione <code>print</code> o ogni oggetto il quale è in grado di stampare il corretto indice dell'oggetto nell'array.</p> - -<div class="blockIndicator note"> -<p>Passare l'oggetto come valore <code>this</code> non è strettamente necessario ma è fatto a scopo esplicativo.</p> -</div> - -<pre class="brush: js">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); -} -</pre> - -<h3 id="Usare_call_per_invocare_una_funzione_e_specificare_il_contesto_per_this">Usare <code>call</code> per invocare una funzione e specificare il contesto per '<code>this</code>'</h3> - -<p>Nell'esempio sotto, quando viene eseguita <code>greet</code>, il valore di <code>this</code> verrà legato all'oggetto <code>obj</code>.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="Usare_call_per_invocare_una_funzione_senza_specificare_il_primo_parametro">Usare <code>call</code> per invocare una funzione senza specificare il primo parametro</h3> - -<p>Nell'esempio sotto, viene invocata la funzione <code>display</code> senza passare il primo parametro. Se il primo parametro non è passato il valore di <code>this</code> è legato all'oggetto globale.</p> - -<pre class="brush: js">var sData = 'Wisen'; - -function display() { - console.log('sData value is %s ', this.sData); -} - -display.call(); // sData value is Wisen</pre> - -<div class="note"> -<p><strong>Attenzione:</strong> In strict mode il valore di <code>this</code> sarà <code>undefined</code>. Vedere sotto.</p> -</div> - -<pre class="brush: js">'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</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specifiche</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.Function.call")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Function.prototype.bind()")}}</li> - <li>{{jsxref("Function.prototype.apply()")}}</li> - <li> - <p><a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a></p> - </li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/function/index.html b/files/it/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index 4ef63fb80b..0000000000 --- a/files/it/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -<div>{{JSRef}}</div> - -<p>The <strong><code>Function</code> constructor</strong> creates a new <code>Function</code> object. In JavaScript every function is actually a <code>Function</code> object.</p> - -<p>gge</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> - <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> - <dt><code>functionBody</code></dt> - <dd>A string containing the JavaScript statements comprising the function definition.</dd> -</dl> - -<h2 id="Description">Description</h2> - -<p><code>Function</code> objects created with the <code>Function</code> constructor are parsed when the function is created. This is less efficient than declaring a function with a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> and calling it within your code, because such functions are parsed with the rest of the code.</p> - -<p>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.</p> - -<div class="note"> -<p><strong>Note:</strong> Functions created with the <code>Function</code> 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 <code>Function</code> constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.</p> -</div> - -<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> - -<h2 id="Properties_and_Methods_of_Function">Properties and Methods of <code>Function</code></h2> - -<p>The global <code>Function</code> 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")}}.</p> - -<h2 id="Function_prototype_object"><code>Function</code> prototype object</h2> - -<h3 id="Properties">Properties</h3> - -<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> - -<h3 id="Methods">Methods</h3> - -<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> - -<h2 id="Function_instances"><code>Function</code> instances</h2> - -<p><code>Function</code> 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 <code>Function</code> instances.</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Specifying_arguments_with_the_Function_constructor">Specifying arguments with the <code>Function</code> constructor</h3> - -<p>The following code creates a <code>Function</code> object that takes two arguments.</p> - -<pre class="brush: js">// 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 -</pre> - -<p>The arguments "<code>a</code>" and "<code>b</code>" are formal argument names that are used in the function body, "<code>return a + b</code>".</p> - -<h3 id="A_recursive_shortcut_to_massively_modify_the_DOM">A recursive shortcut to massively modify the DOM</h3> - -<p>Creating functions with the <code>Function</code> 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 <code>Function</code> constructor for each new query if you want to avoid closures.</p> - -<pre class="brush: html"><!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> -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Functions", "Functions and function scope")}}</li> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("Statements/function", "function statement")}}</li> - <li>{{jsxref("Operators/function", "function expression")}}</li> - <li>{{jsxref("Statements/function*", "function* statement")}}</li> - <li>{{jsxref("Operators/function*", "function* expression")}}</li> - <li>{{jsxref("GeneratorFunction")}}</li> -</ul> 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 deleted file mode 100644 index 6e305fb3ed..0000000000 --- a/files/it/web/javascript/reference/global_objects/function/length/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Function.length -slug: Web/JavaScript/Reference/Global_Objects/Function/length -translation_of: Web/JavaScript/Reference/Global_Objects/Function/length ---- -<div>{{JSRef}}</div> - -<p>La proprietà <code><strong>length</strong></code> indica il numero di parametri che la funzione si aspetta di ricevere.</p> - -<p>{{EmbedInteractiveExample("pages/js/function-length.html")}}</p> - - - -<div>{{js_property_attributes(0,0,1)}}</div> - -<h2 id="Description">Description</h2> - -<p><code>length</code> è 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.</p> - -<h3 id="Data_property_of_the_Function_constructor">Data property of the Function constructor</h3> - -<p>Il costruttore {{jsxref("Function")}} è esso stesso un oggetto {{jsxref("Function")}}. La sua proprietà <code>length</code> ha valore 1. Gli attributi delle proprietà sono: Writable: <code>false</code>, Enumerable: <code>false</code>, Configurable: <code>false</code>.</p> - -<h3 id="Property_of_the_Function_prototype_object">Property of the Function prototype object</h3> - -<p>La proprietà <code>length</code> del prototype di un oggetto {{jsxref("Function")}} ha valore 0.</p> - -<h2 id="Examples">Examples</h2> - -<pre class="brush: js">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</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.1.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Gli attributi <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">configurabili</span></font> di queste proprietà diventano <code>true</code>.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Function.length")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Function")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/generator/index.html b/files/it/web/javascript/reference/global_objects/generator/index.html deleted file mode 100644 index b950dd8216..0000000000 --- a/files/it/web/javascript/reference/global_objects/generator/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>The <code><strong>Generator</strong></code> object is returned by a {{jsxref("Statements/function*", "generator function", "", 1)}} and it conforms to both the <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable">iterable protocol</a> and the <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">iterator protocol</a>.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">function* gen() { - yield 1; - yield 2; - yield 3; -} - -var g = gen(); // "Generator { }"</pre> - -<h2 id="Methods">Methods</h2> - -<dl> - <dt>{{jsxref("Generator.prototype.next()")}}</dt> - <dd>Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression.</dd> - <dt>{{jsxref("Generator.prototype.return()")}}</dt> - <dd>Returns the given value and finishes the generator.</dd> - <dt>{{jsxref("Generator.prototype.throw()")}}</dt> - <dd>Throws an error to a generator.</dd> -</dl> - -<h2 id="Example">Example</h2> - -<h3 id="An_infinite_iterator">An infinite iterator</h3> - -<pre class="brush: js">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 -// ...</pre> - -<h2 id="Legacy_generator_objects">Legacy generator objects</h2> - -<p>Firefox (SpiderMonkey) also implements an earlier version of generators in <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a>, where the star (*) in the function declaration was not necessary (you just use the <code>yield</code> keyword in the function body). However, legacy generators are deprecated. Do not use them; they are going to be removed ({{bug(1083482)}}).</p> - -<h3 id="Legacy_generator_methods">Legacy generator methods</h3> - -<dl> - <dt><code>Generator.prototype.next() </code>{{non-standard_inline}}</dt> - <dd>Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression. This corresponds to <code>next()</code> in the ES2015 generator object.</dd> - <dt><code>Generator.prototype.close()</code> {{non-standard_inline}}</dt> - <dd>Closes the generator, so that when calling <code>next()</code> an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the <code>return()</code> method in the ES2015 generator object.</dd> - <dt><code>Generator.prototype.send()</code> {{non-standard_inline}}</dt> - <dd>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. <code>send(x)</code> corresponds to <code>next(x)</code> in the ES2015 generator object.</dd> - <dt><strong><code>Generator.</code></strong><code>prototype.</code><strong><code>throw()</code> </strong> {{non-standard_inline}}</dt> - <dd>Throws an error to a generator. This corresponds to the <code>throw()</code> method in the ES2015 generator object.</dd> -</dl> - -<h3 id="Legacy_generator_example">Legacy generator example</h3> - -<pre class="brush: js">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) -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatChrome(39.0)}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Android Webview</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - <th>Chrome for Android</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(39.0)}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(39.0)}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<h3 id="Legacy_generators">Legacy generators</h3> - -<ul> - <li>{{jsxref("Statements/Legacy_generator_function", "The legacy generator function", "", 1)}}</li> - <li>{{jsxref("Operators/Legacy_generator_function", "The legacy generator function expression", "", 1)}}</li> - <li>{{jsxref("StopIteration")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol">The legacy Iterator protocol</a></li> -</ul> - -<h3 id="ES2015_generators">ES2015 generators</h3> - -<ul> - <li>{{jsxref("Functions", "Functions", "", 1)}}</li> - <li>{{jsxref("Statements/function", "function")}}</li> - <li>{{jsxref("Operators/function", "function expression")}}</li> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("Statements/function*", "function*")}}</li> - <li>{{jsxref("Operators/function*", "function* expression")}}</li> - <li>{{jsxref("GeneratorFunction")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> -</ul> 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 deleted file mode 100644 index 03408534d5..0000000000 --- a/files/it/web/javascript/reference/global_objects/generator/next/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Generator.prototype.next() -slug: Web/JavaScript/Reference/Global_Objects/Generator/next -translation_of: Web/JavaScript/Reference/Global_Objects/Generator/next ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>next</strong></code><strong><code>()</code></strong> ritorna un oggetto con due proprietà <code>done</code> and <code>value</code>. Puoi anche fornire un parametro al metodo next per trasmettere un valore al generatore.</p> - -<h2 id="Syntassi">Syntassi</h2> - -<pre class="syntaxbox"><code><var>gen</var>.next(value)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>value</code></dt> - <dd>Il valore trasmesso al generatore</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<p>Un <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Oggetto</a> con due proprietà:</p> - -<ul> - <li><code>done</code> (boolean) - - <ul> - <li>Ha il valore <code>true</code> se l' iteratore è oltre la fine della sequenza iterata. In questo caso <code>value</code> opzionalmente specifica <em>il valore di ritorno</em> dell' iteratore.</li> - <li>Ha il valore <code>false</code> se l'iteratore è stato capace di generare il valore successivo nella sequenza. Questo equivale nello non specificare la proprietà done interamente.</li> - </ul> - </li> - <li><code>value</code> - ogni valore Javascript ritornato dall'iteratore. Può essere omesso quando done è true</li> -</ul> - -<h2 id="Examples">Examples</h2> - -<h3 id="Using_next()">Using <code>next()</code></h3> - -<p><font face="Consolas, Liberation Mono, Courier, monospace">Il seguente esempio mostra semplice generatore e un oggetto che il metodo next ritorna:</font></p> - -<pre class="brush: js">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 }" -</pre> - -<h3 id="Mandare_valori_al_generatore">Mandare valori al generatore</h3> - -<p>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. </p> - -<p> </p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-generator.prototype.next', 'Generator.prototype.next')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-generator.prototype.next', 'Generator.prototype.next')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Edge</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>13</td> - <td>{{CompatGeckoDesktop(26)}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatSafari(10)}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>5.1</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile(26)}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>10</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators and generators</a></li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/index.html b/files/it/web/javascript/reference/global_objects/index.html deleted file mode 100644 index 3cddb3fc08..0000000000 --- a/files/it/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Standard built-in objects -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - Refernce - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects ---- -<div>{{jsSidebar("Objects")}}</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>Questo capitolo documenta tutti gli oggetti standard predefiiti di JavaScript, con i loro metodi e le loro proprietà.</p> - -<p>Il termine "oggetti globali" (o oggetti standard predefiniti) non va confuso con il termine <em>oggetto globale</em>. In questa documentazione, "oggetti globali" si riferisce agli <em>oggetti nel contesto globale</em> (ma solo se non viene utilizzata la modalità strict di ECMAScript5, altrimenti restituisce {{jsxref("Global_Objects/undefined", "undefined")}}). Si piuò accedere all'<em>oggetto globale</em> usando l'operatore {{jsxref("Operators/this", "this")}} nel contesto globale. Infatti il contesto globale consiste nell'insieme di tutte le properietà dell'<em>oggetto globale</em>.</p> - -<p>Altri oggetti nel contesto globale possono essere <a href="/it/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">creati dallo script</a> o dall'applicazione utilizzata (ad esempio, un browser). Gli oggetti forniti dal browser sono documentati nella sezione <a href="/it/docs/Web/API/Reference">API reference</a>. Per altre informazioni riguardo la differenza tra il <a href="/it/docs/DOM/DOM_Reference">DOM</a> e <a href="/it/docs/Web/JavaScript">JavaScript</a> base, vedi la <a href="/it/docs/Web/JavaScript/JavaScript_technologies_overview">panoramica sulle tecnologie JavaScript</a>.</p> - -<div class="onlyinclude"> -<h2 id="Oggetti_standard_(per_categoria)">Oggetti standard (per categoria)</h2> - -<h3 id="Valori">Valori</h3> - -<p>Varabili globali che rappresentano un valore semplice, non hanno altre proprietà o metodi.</p> - -<ul> - <li>{{jsxref("Infinity")}}</li> - <li>{{jsxref("NaN")}}</li> - <li>{{jsxref("undefined")}}</li> - <li>{{jsxref("null")}} literal</li> -</ul> - -<h3 id="Funzioni">Funzioni</h3> - -<p>Queste funzioni globali che vengono richiamate direttamente restituiscono direttamente il risultato al chiamante</p> - -<ul> - <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> - <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</li> - <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> - <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> - <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> - <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> - <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> - <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> - <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> - <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</li> - <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</li> -</ul> - -<h3 id="Oggetti_fondamentali">Oggetti fondamentali</h3> - -<p>Oggetti generali di Javascrpt, sui quali sono basati tutti gli altri oggetti. Rappresentano oggetti, funzioni ed errori.</p> - -<ul> - <li>{{jsxref("Object")}}</li> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("Boolean")}}</li> - <li>{{jsxref("Symbol")}}</li> - <li>{{jsxref("Error")}}</li> - <li>{{jsxref("EvalError")}}</li> - <li>{{jsxref("InternalError")}}</li> - <li>{{jsxref("RangeError")}}</li> - <li>{{jsxref("ReferenceError")}}</li> - <li>{{jsxref("SyntaxError")}}</li> - <li>{{jsxref("TypeError")}}</li> - <li>{{jsxref("URIError")}}</li> -</ul> - -<h3 id="Numeri_e_date">Numeri e date</h3> - -<p>Oggetti usati per rappresentare numeri, date e calcoli matematici.</p> - -<ul> - <li>{{jsxref("Number")}}</li> - <li>{{jsxref("Math")}}</li> - <li>{{jsxref("Date")}}</li> -</ul> - -<h3 id="Elaborazione_del_testo">Elaborazione del testo</h3> - -<p>Oggetti che rappresentano le stringe o il supporto per manipolarle.</p> - -<ul> - <li>{{jsxref("String")}}</li> - <li>{{jsxref("RegExp")}}</li> -</ul> - -<h3 id="Collezioni_ordinate">Collezioni ordinate</h3> - -<p>Questi oggetti rappresentano delle collezioni di dati che sono ordinati secondo un indice. Includono array tipizzati ed costruttori simili ad array.</p> - -<ul> - <li>{{jsxref("Array")}}</li> - <li>{{jsxref("Int8Array")}}</li> - <li>{{jsxref("Uint8Array")}}</li> - <li>{{jsxref("Uint8ClampedArray")}}</li> - <li>{{jsxref("Int16Array")}}</li> - <li>{{jsxref("Uint16Array")}}</li> - <li>{{jsxref("Int32Array")}}</li> - <li>{{jsxref("Uint32Array")}}</li> - <li>{{jsxref("Float32Array")}}</li> - <li>{{jsxref("Float64Array")}}</li> -</ul> - -<h3 id="Collezioni_chiave-valore">Collezioni chiave-valore</h3> - -<p>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.</p> - -<ul> - <li>{{jsxref("Map")}}</li> - <li>{{jsxref("Set")}}</li> - <li>{{jsxref("WeakMap")}}</li> - <li>{{jsxref("WeakSet")}}</li> -</ul> - -<h3 id="Dati_strutturati">Dati strutturati</h3> - -<p>Oggetti che rappresentano e interagiscono con buffer di dati e con dati codificati utilizzando <em>JavaScript Object Notation</em> (JSON).</p> - -<ul> - <li>{{jsxref("ArrayBuffer")}}</li> - <li>{{jsxref("SharedArrayBuffer")}} {{experimental_inline}}</li> - <li>{{jsxref("Atomics")}} {{experimental_inline}}</li> - <li>{{jsxref("DataView")}}</li> - <li>{{jsxref("JSON")}}</li> -</ul> - -<h3 id="Oggetti_di_controllo_dell'astrazione">Oggetti di controllo dell'astrazione</h3> - -<ul> - <li>{{jsxref("Promise")}}</li> - <li>{{jsxref("Generator")}}</li> - <li>{{jsxref("GeneratorFunction")}}</li> - <li>{{experimental_inline}} {{jsxref("AsyncFunction")}}</li> -</ul> - -<h3 id="Reflection">Reflection</h3> - -<ul> - <li>{{jsxref("Reflect")}}</li> - <li>{{jsxref("Proxy")}}</li> -</ul> - -<h3 id="Internazionalizzazione">Internazionalizzazione</h3> - -<p>Oggetti aggiunti a ECMAScript per le funzionalità che dipendono dalla lingua.</p> - -<ul> - <li>{{jsxref("Intl")}}</li> - <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> - <li>{{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> - <li>{{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> -</ul> - -<p> </p> - -<h3 id="WebAssembly">WebAssembly</h3> - -<ul> - <li>{{jsxref("WebAssembly")}}</li> - <li>{{jsxref("WebAssembly.Module")}}</li> - <li>{{jsxref("WebAssembly.Instance")}}</li> - <li>{{jsxref("WebAssembly.Memory")}}</li> - <li>{{jsxref("WebAssembly.Table")}}</li> - <li>{{jsxref("WebAssembly.CompileError")}}</li> - <li>{{jsxref("WebAssembly.LinkError")}}</li> - <li>{{jsxref("WebAssembly.RuntimeError")}}</li> -</ul> - -<p> </p> - -<h3 id="Altro">Altro</h3> - -<ul> - <li>{{jsxref("Functions/arguments", "arguments")}}</li> -</ul> -</div> - -<p> </p> diff --git a/files/it/web/javascript/reference/global_objects/infinity/index.html b/files/it/web/javascript/reference/global_objects/infinity/index.html deleted file mode 100644 index 48b983e107..0000000000 --- a/files/it/web/javascript/reference/global_objects/infinity/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Infinity -slug: Web/JavaScript/Reference/Global_Objects/Infinity -translation_of: Web/JavaScript/Reference/Global_Objects/Infinity ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La proprietà globale <strong><code>Infinity</code></strong> è un valore numerico che rappresenta l'infinito.</p> - -<p>{{js_property_attributes(0,0,0)}}</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>Infinity </code></pre> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p><code>Infinity</code> è una proprietà dell'<em>oggetto globale</em>, ossia una variabile nell'ambito globale.</p> - -<p>Il valore iniziale di <code>Infinity</code> è {{jsxref("Number.POSITIVE_INFINITY")}}. Il valore <code>Infinity</code> (infinito positivo) è maggiore di ogni altro numero. Matematicamente questo valore si comporta come l'infinito: per esempio, qualsiasi numero positivo moltipilicato per <code>Infinity</code> è uguale a <code>Infinity</code>, e qualsiasi numero diviso per <code>Infinity</code> è uguale a 0.</p> - -<p>Secondo la specifica ECMAScript5, <code>Infinity</code> è accessibile in sola lettura (implementato in JavaScript 1.8.5 / Firefox 4).</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Definizione iniziale. Implementato in JavaScript 1.3</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.1.2', 'Infinity')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also" name="See_also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> - <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/isfinite/index.html b/files/it/web/javascript/reference/global_objects/isfinite/index.html deleted file mode 100644 index ee250b9410..0000000000 --- a/files/it/web/javascript/reference/global_objects/isfinite/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: isFinite() -slug: Web/JavaScript/Reference/Global_Objects/isFinite -translation_of: Web/JavaScript/Reference/Global_Objects/isFinite ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione globale <strong><code>isFinite()</code></strong> determina se il parametro passatole è un numero finito. Se necessario, il parametro viene prima convertito in un valore numerico.</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox">isFinite(<em>number</em>)</pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><font face="Consolas, Monaco, Andale Mono, monospace">number</font></dt> - <dd>Il valore da controllare che sia finito.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p><code>isFinite</code> è una funzione globale.</p> - -<p>Puoi usare questa funzione per determinare se un numero è finito. La funzione <code>isFinite</code> restituisce <code>false</code> se il valore passatole è {{jsxref("NaN")}}, {{jsxref("Infinity")}} (infinito positivo) o <code>-</code>{{jsxref("Infinity")}} (infinito negativo); altrimenti restituisce <code>true</code>.</p> - -<h2 id="Examples" name="Examples">Esempi</h2> - -<pre class="brush: js">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. -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 2nd Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_Also" name="See_Also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Number.isFinite()")}}</li> - <li>{{jsxref("Number.NaN")}}</li> - <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> - <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/isnan/index.html b/files/it/web/javascript/reference/global_objects/isnan/index.html deleted file mode 100644 index db6ebc85d8..0000000000 --- a/files/it/web/javascript/reference/global_objects/isnan/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: isNaN() -slug: Web/JavaScript/Reference/Global_Objects/isNaN -translation_of: Web/JavaScript/Reference/Global_Objects/isNaN ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>isNaN()</code></strong> determina se un valore è {{jsxref("NaN")}} o no.</p> - -<div class="note"> -<p><strong>Nota:</strong> le conversioni di tipo nella funzione <code>isNaN</code> 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")}}.</p> -</div> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>isNaN(<em>number</em>)</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>number</code></dt> - <dd>Il valore da controllare.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<h3 id="The_necessity_of_an_isNaN_function" name="The_necessity_of_an_isNaN_function">La necessità di una funzione <code>isNaN()</code></h3> - -<p>A differenza di tutti gli altri valori in JavaScript, non è possibile usare gli operatori di uguaglianza (<code>==</code> e <code>===</code>) per determinare se un valore è {{jsxref("NaN")}} oppure no, perché entrambe le uguaglianze <code>NaN == NaN</code> e <code>NaN === NaN</code> vengono considerate false. Ecco perché è necessaria una funzione <code>isNaN()</code>.</p> - -<h3 id="Origin_of_NaN_values" name="Origin_of_NaN_values">L'origine del valore <code>NaN</code></h3> - -<p>Il valore <code>NaN</code> è generato da un'operazione aritmetica il cui risultato è {{jsxref("undefined")}} o un valore <em>non rappresentabile</em>. Tali valori non rappresentano necessariamente un valore oltre i limiti. <code>NaN</code> può anche essere il risultato del trasformare valori non-numerici dai quali non è possibile ottenere un numero in numeri.</p> - -<p>Per esempio, dividere zero per zero restituisce <font face="Consolas, Monaco, Andale Mono, monospace">NaN</font>, ma dividere un qualsiasi altro numero per zero no.</p> - -<h3 id="Comportamenti_particolari">Comportamenti particolari</h3> - -<p>Già dalla prima versione della specifica della funzione <code>isNaN</code>, il suo comportamento con valori non-numerici può confondere. Quando il parametro della funzione <code>isNaN</code> 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 <code>NaN</code> la funzione restituisce <code>false</code>. La stringa vuota, per esempio, suciramente non è un numero, ma la funzione restituisce <code>false</code>. La confusione nasce dal fatto che il termine "not a number" (rappresentato da <code>NaN</code>) 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?"</p> - -<p>La prossima versione di ECMAScript (ES6) definiesce la funzione {{jsxref("Number.isNaN()")}}. <code>Number.isNaN()</code>, che ritorna <code>false</code> per tutti i valori non-numerici, sarà un metodo affidabile per sapere se un numero è <code>NaN</code> o no. In assenza di <code>Number.isNaN</code>, l'espressione <code>(x !== x)</code> è il metodo più affidabile per determinare se un numero è <code>NaN</code> oppure no, perché evita i falsi positivi generati dalla funzione <code>isNaN()</code>.</p> - -<h2 id="Examples" name="Examples">Esempi</h2> - -<pre class="brush: js">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</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: open sans light,sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also" name="See_also">Vedi anche</h2> - -<ul> - <li>{{jsxref("NaN")}}</li> - <li>{{jsxref("Number.isNaN()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/json/index.html b/files/it/web/javascript/reference/global_objects/json/index.html deleted file mode 100644 index caa08b766f..0000000000 --- a/files/it/web/javascript/reference/global_objects/json/index.html +++ /dev/null @@ -1,244 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>The <strong><code>JSON</code></strong> object contains methods for parsing <a class="external" href="http://json.org/">JavaScript Object Notation</a> ({{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.</p> - -<h2 id="Description">Description</h2> - -<h3 id="JavaScript_Object_Notation">JavaScript Object Notation</h3> - -<p>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 <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">JSON: The JavaScript subset that isn't</a>.</p> - -<table> - <caption>JavaScript and JSON differences</caption> - <thead> - <tr> - <th scope="col">JavaScript type</th> - <th scope="col">JSON differences</th> - </tr> - </thead> - <tbody> - <tr> - <td>Objects and Arrays</td> - <td>Property names must be double-quoted strings; trailing commas are forbidden.</td> - </tr> - <tr> - <td>Numbers</td> - <td>Leading zeros are prohibited; a decimal point must be followed by at least one digit.</td> - </tr> - <tr> - <td>Strings</td> - <td> - <p>Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (<a href="http://unicode-table.com/en/2028/">U+2028</a>) and paragraph separator (<a href="http://unicode-table.com/en/2029/">U+2029</a>) 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:</p> - - <pre class="brush: js"> -var code = '"\u2028\u2029"'; -JSON.parse(code); // works fine -eval(code); // fails -</pre> - </td> - </tr> - </tbody> -</table> - -<p>The full JSON syntax is as follows:</p> - -<pre><var>JSON</var> = <strong>null</strong> - <em>or</em> <strong>true</strong> <em>or</em> <strong>false</strong> - <em>or</em> <var>JSONNumber</var> - <em>or</em> <var>JSONString</var> - <em>or</em> <var>JSONObject</var> - <em>or</em> <var>JSONArray</var> - -<var>JSONNumber</var> = <strong>-</strong> <var>PositiveNumber</var> - <em>or</em> <var>PositiveNumber</var> -<var>PositiveNumber</var> = DecimalNumber - <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> - <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> <var>ExponentPart</var> - <em>or</em> <var>DecimalNumber</var> <var>ExponentPart</var> -<var>DecimalNumber</var> = <strong>0</strong> - <em>or</em> <var>OneToNine</var> <var>Digits</var> -<var>ExponentPart</var> = <strong>e</strong> <var>Exponent</var> - <em>or</em> <strong>E</strong> <var>Exponent</var> -<var>Exponent</var> = <var>Digits</var> - <em>or</em> <strong>+</strong> <var>Digits</var> - <em>or</em> <strong>-</strong> <var>Digits</var> -<var>Digits</var> = <var>Digit</var> - <em>or</em> <var>Digits</var> <var>Digit</var> -<var>Digit</var> = <strong>0</strong> through <strong>9</strong> -<var>OneToNine</var> = <strong>1</strong> through <strong>9</strong> - -<var>JSONString</var> = <strong>""</strong> - <em>or</em> <strong>"</strong> <var>StringCharacters</var> <strong>"</strong> -<var>StringCharacters</var> = <var>StringCharacter</var> - <em>or</em> <var>StringCharacters</var> <var>StringCharacter</var> -<var>StringCharacter</var> = any character - <em>except</em> <strong>"</strong> <em>or</em> <strong>\</strong> <em>or</em> U+0000 through U+001F - <em>or</em> <var>EscapeSequence</var> -<var>EscapeSequence</var> = <strong>\"</strong> <em>or</em> <strong>\/</strong> <em>or</em> <strong>\\</strong> <em>or</em> <strong>\b</strong> <em>or</em> <strong>\f</strong> <em>or</em> <strong>\n</strong> <em>or</em> <strong>\r</strong> <em>or</em> <strong>\t</strong> - <em>or</em> <strong>\u</strong> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> -<var>HexDigit</var> = <strong>0</strong> through <strong>9</strong> - <em>or</em> <strong>A</strong> through <strong>F</strong> - <em>or</em> <strong>a</strong> through <strong>f</strong> - -<var>JSONObject</var> = <strong>{</strong> <strong>}</strong> - <em>or</em> <strong>{</strong> <var>Members</var> <strong>}</strong> -<var>Members</var> = <var>JSONString</var> <strong>:</strong> <var>JSON</var> - <em>or</em> <var>Members</var> <strong>,</strong> <var>JSONString</var> <strong>:</strong> <var>JSON</var> - -<var>JSONArray</var> = <strong>[</strong> <strong>]</strong> - <em>or</em> <strong>[</strong> <var>ArrayElements</var> <strong>]</strong> -<var>ArrayElements</var> = <var>JSON</var> - <em>or</em> <var>ArrayElements</var> <strong>,</strong> <var>JSON</var> -</pre> - -<p>Insignificant whitespace may be present anywhere except within a <code><var>JSONNumber</var></code> (numbers must contain no whitespace) or <code><var>JSONString</var></code> (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (<a href="http://unicode-table.com/en/0009/">U+0009</a>), carriage return (<a href="http://unicode-table.com/en/000D/">U+000D</a>), line feed (<a href="http://unicode-table.com/en/000A/">U+000A</a>), and space (<a href="http://unicode-table.com/en/0020/">U+0020</a>) characters are the only valid whitespace characters.</p> - -<h2 id="Methods">Methods</h2> - -<dl> - <dt>{{jsxref("JSON.parse()")}}</dt> - <dd>Parse a string as JSON, optionally transform the produced value and its properties, and return the value.</dd> - <dt>{{jsxref("JSON.stringify()")}}</dt> - <dd>Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.</dd> -</dl> - -<h2 id="Polyfill">Polyfill</h2> - -<p>The <code>JSON</code> 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 <code>JSON</code> object in implementations which do not natively support it (like Internet Explorer 6).</p> - -<p>The following algorithm is an imitation of the native <code>JSON</code> object:</p> - -<pre class="brush: js">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) + '"'; - }; - })() - }; -} -</pre> - -<p>More complex well-known <a class="external" href="http://remysharp.com/2010/10/08/what-is-a-polyfill/">polyfills</a> for the <code>JSON</code> object are <a class="link-https" href="https://github.com/douglascrockford/JSON-js">JSON2</a> and <a class="external" href="http://bestiejs.github.com/json3">JSON3</a>.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-json-object', 'JSON')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("1.9.1")}}</td> - <td>{{CompatIE("8.0")}}</td> - <td>{{CompatOpera("10.5")}}</td> - <td>{{CompatSafari("4.0")}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("1.0")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Date.prototype.toJSON()")}}</li> -</ul> 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 deleted file mode 100644 index f5c823ddf1..0000000000 --- a/files/it/web/javascript/reference/global_objects/json/parse/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p><span class="seoSummary">Il metodo <strong><code>JSON.parse()</code></strong> analizza una stringa JSON, costruendo il valore JavaScript o l'oggetto descritto dalla stringa. È possibile fornire una funzione <strong>reviver</strong> opzionale per eseguire una trasformazione sull'oggetto risultante prima che venga restituito.</span></p> - -<div>{{EmbedInteractiveExample("pages/js/json-parse.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">JSON.parse(<var>text</var>[, <var>reviver</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>text</code></dt> - <dd>La stringa da analizzare come JSON. Vedi l'oggetto {{jsxref("JSON")}} per una descrizione della sintassi JSON.</dd> - <dt><code>reviver</code> {{optional_inline}}</dt> - <dd>Se una funzione, questo prescrive come viene trasformato il valore originariamente prodotto dall'analisi, prima di essere restituito.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>{{jsxref("Object")}} corrispondente al parametro JSON <code>text</code> dato.</p> - -<h3 id="Eccezione">Eccezione</h3> - -<p>Genera un errore {{jsxref("SyntaxError")}} se la stringa da analizzare non è JSON valida.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzare_JSON.parse()">Utilizzare <code>JSON.parse()</code></h3> - -<pre class="brush: js">JSON.parse('{}'); // {} -JSON.parse('true'); // true -JSON.parse('"foo"'); // "foo" -JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] -JSON.parse('null'); // null -</pre> - -<h3 id="Usare_il_parametro_reviver">Usare il parametro <code>reviver</code></h3> - -<p>Se viene specificato un <code>reviver</code>, 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 <code>reviver</code>. Quindi viene chiamato, con l'oggetto contenente la proprietà da elaborare come <code>this</code>, e con il nome della proprietà come stringa e il valore della proprietà come argomenti. Se la funzione <code>reviver</code> 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.</p> - -<p>Se <code>reviver</code> 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.</p> - -<pre class="brush: js">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 -// "" -</pre> - -<h3 id="JSON.parse()_non_consente_virgole_finali"><code>JSON.parse()</code> non consente virgole finali</h3> - -<pre class="example-bad brush: js example-bad">// both will throw a SyntaxError -JSON.parse('[1, 2, 3, 4, ]'); -JSON.parse('{"foo" : 1, }'); -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.7.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatiblità_con_i_browser">Compatiblità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.JSON.parse")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("JSON.stringify()")}}</li> -</ul> 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 deleted file mode 100644 index 9a0bf5f812..0000000000 --- a/files/it/web/javascript/reference/global_objects/json/stringify/index.html +++ /dev/null @@ -1,325 +0,0 @@ ---- -title: JSON.stringify() -slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify -translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify ---- -<div>{{JSRef}}</div> - -<div> </div> - -<p>Il metodo <strong><code>JSON.stringify()</code></strong> 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.</p> - -<div>{{EmbedInteractiveExample("pages/js/json-stringify.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>JSON.stringify(<var>value</var>[, <var>replacer</var>[, <var>space</var>]])</code></pre> - -<h3 id="Parametri">Parametri<a id="parametri" name="parametri"></a></h3> - -<dl> - <dt><code>value</code></dt> - <dd>Il valore da convertire in stringa JSON.</dd> - <dt><code>replacer</code>{{optional_inline}}</dt> - <dd>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.</dd> - <dt><font face="Consolas, Liberation Mono, Courier, monospace"><code>space</code></font>{{optional_inline}}</dt> - <dd>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 <code>Number</code>, indica il numero di caratteri dello spazio da usare come spazio bianco; questo numero è limitato a 10 (se è maggiore, il valore è solo <code>10</code>).Valori inferiori a 1 indicano che non deve essere usato alcuno spazio.</dd> - <dd> - <p>Se si tratta di una <code>String</code>, 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.</p> - - <h3 id="Valore_di_ritorno">Valore di ritorno<a id="Valore_di_Ritorno" name="Valore_di_Ritorno"></a></h3> - - <p>Una stringa JSON che rappresenta il valore dato.</p> - - <h3 id="Eccezioni_2">Eccezioni<a id="Eccezioni" name="Eccezioni"></a></h3> - - <p>Genera un'eccezione {{JSxRef("TypeError")}} ("valore dell'oggetto ciclico") quando viene trovato un riferimento circolare.</p> - </dd> -</dl> - -<h2 id="Descrizione">Descrizione<a id="descrizione" name="descrizione"></a></h2> - -<p><code>JSON.stringify()</code> converte un valore in notazione JSON che lo rappresenta:</p> - -<ul> - <li>Se il valore ha un metodo <a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Comportamento_di_toJSON()">toJSON()</a> è responsabile definire quali dati verranno serializzati.</li> - <li>Gli oggetti {{JSxRef("Boolean")}}, {{JSxRef("Number")}}, e {{JSxRef("String")}} vengono convertiti ai corrispondenti valori primitivi durante la stringificazione, in accordo con la semantica di conversione tradizionale.</li> - <li>Se si incontrano {{JSxRef("undefined")}}, una {{JSxRef("Function")}}, o un {{JSxRef("Symbol")}} durante la conversione, viene omesso (quando viene trovato in un oggetto) o viene censurato {{JSxRef("null")}} (quando viene trovato in un array). <code>JSON.stringify()</code> può anche restituire <code>undefined</code> quando si passa in valori "puri" come <code>JSON.stringify(function(){})</code> o <code>JSON.stringify(undefined)</code>.</li> - <li>Tutte le proprietà <a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Symbol" title='The Symbol() function returns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class but is incomplete as a constructor because it does not support the syntax "new Symbol()".'><code>Symbol</code></a>-keyed <font><font>saranno completamente ignorate, anche quando si utilizza la funzione </font></font><code>replacer</code><font><font>.</font></font></li> - <li><font><font>Le istanze di </font></font><a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Date" title="Crea un'istanza Date JavaScript che rappresenta un singolo momento nel tempo. Gli oggetti data sono basati su un valore temporale che è il numero di millisecondi dal 1 ° gennaio 1970 UTC."><code>Date</code></a> <font><font>implementano la funzione </font></font><code>toJSON()</code><font><font> restituendo una stringa (la stessa di </font></font><code>date.toISOString()</code><font><font>). </font><font>Quindi, sono trattati come stringhe.</font></font></li> -</ul> - -<pre class="brush: js">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"}' - -</pre> - -<h3 id="Il_parametro_replacer">Il parametro <code>replacer</code></h3> - -<p><font><font>Il parametro </font></font><code>replacer</code><font><font> può essere una funzione o un array.</font></font></p> - -<p><strong><font><font>Come una funzione</font></font></strong><font><font>, prende due parametri: la </font></font><var><font><font>chiave</font></font></var><font><font> e il </font></font><var><font><font>valore che si</font></font></var><font><font> sta stringendo. </font><font>L'oggetto in cui è stata trovata la chiave viene fornito come il parametro </font></font><code>this</code><font><font> </font><font>del replacer.</font></font></p> - -<p><font><font>Inizialmente, la funzione <code>replacer</code> 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.</font></font></p> - -<ul> - <li>Se si restituisce un {{jsxref("Number")}}, la stringa corrispondente a quel numero viene utilizzata come valore per la proprietà quando viene aggiunta alla stringa JSON.</li> - <li>Se si restituisce una {{jsxref("String")}}, tale stringa viene utilizzata come valore della proprietà quando viene aggiunta alla stringa JSON.</li> - <li>Se si restituisce un {{jsxref("Boolean")}}, "true" o "false" viene utilizzato come valore della proprietà, come appropriato, quando viene aggiunto alla stringa JSON.</li> - <li><font><font>Se torni </font></font><code>null</code><font><font>, </font></font><code>null</code> <font><font>verrà aggiunto alla stringa JSON.</font></font></li> - <li>Se si restituisce un qualsiasi altro oggetto, <font><font>l'oggetto viene ricorsivamente stringa nella stringa JSON, chiamando la funzione </font></font><code>replacer</code><font><font> su ogni proprietà, a meno che l'oggetto non sia una funzione, nel qual caso non viene aggiunto nulla alla stringa JSON.</font></font></li> - <li>Se si restituisce <code>undefined</code>, la proprietà non è inclusa (cioè filtrata) nella stringa JSON di output.</li> -</ul> - -<div class="note"><strong>Nota:</strong> N<font><font>on è possibile utilizzare la </font></font><code>replacer</code><font><font>funzione per rimuovere i valori da una matrice. </font><font>Se si restituisce </font></font><code>undefined</code><font><font>o una funzione, </font></font><code>null</code><font><font>viene invece utilizzata.</font></font></div> - -<div class="note">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).</div> - -<h4 id="Esempio_di_replacer_come_funzione">Esempio di <em>replacer, </em>come funzione</h4> - -<pre><code>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}'</code> -</pre> - -<h4 id="Esempio_di_replacer_come_array">Esempio di <em>replacer</em>, come array</h4> - -<p><font><font>Se </font></font><code>replacer</code> <font><font>è un array, i valori dell'array indicano i nomi delle proprietà nell'oggetto che dovrebbero essere incluse nella stringa JSON risultante.</font></font></p> - -<pre class="brush: js">JSON.stringify(foo, ['week', 'month']); -// '{"week":45,"month":7}', mantiene solo le proprietà "week" e "month" -</pre> - -<h3 id="Il_parametro_space">Il parametro <code>space<a id="parametro_space" name="parametro_space"></a></code></h3> - -<p><font><font>L'argomento </font></font><code>space</code><font><font> può essere usato per controllare la spaziatura nella stringa finale.</font></font></p> - -<ul> - <li><strong><font><font>Se si tratta di un numero</font></font></strong><font><font>, i livelli successivi nella stringa verranno rientrati da questi caratteri di spazio (fino a 10).</font></font></li> - <li><strong><font><font>Se è una stringa</font></font></strong><font><font>, i livelli successivi saranno rientrati da questa stringa (o dai primi dieci caratteri di essa).</font></font></li> -</ul> - -<pre><code>JSON.stringify({ a: 2 }, null, ' '); -// '{ -// "a": 2 -// }'</code></pre> - -<p>L'utilizzo di un carattere di tabulazione simula l'aspetto standard di tipo "pretty-print":</p> - -<pre class="brush: js">JSON.stringify({ uno: 1, dos: 2 }, null, '\t'); -// restituisce la stringa: -// '{ -// "uno": 1, -// "dos": 2 -// }' -</pre> - -<h3 id="Comportamento_di_toJSON()">Comportamento di <code>toJSON()</code><a id="comportamento_tojson" name="comportamento_tojson"></a></h3> - -<p><font><font>Se un oggetto da stringificare ha una proprietà denominata il </font></font><code>toJSON</code> <font><font>cui valore è una funzione, il metodo </font></font><code>toJSON()</code> <font><font>personalizza il comportamento di stringificazione JSON: invece dell'oggetto serializzato, il valore restituito dal metodo </font></font><code>toJSON()</code> <font><font>quando chiamato verrà serializzato. </font></font><code>JSON.stringify()</code> <font><font>chiama </font></font><code>toJSON</code> <font><font>con un parametro:</font></font></p> - -<ul> - <li><font><font>se questo oggetto è un valore di proprietà, il nome della proprietà</font></font></li> - <li><font><font>se è in una matrice, l'indice nella matrice, come una stringa</font></font></li> - <li><font><font>una stringa vuota se è </font></font><code>JSON.stringify()</code> <font><font>stata richiamata direttamente su questo oggetto</font></font></li> -</ul> - -<p>Per esempio:</p> - -<pre><code>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'"]'</code> -</pre> - -<h3 id="Problema_con_JSON.stringify()_durante_la_serializzazione_di_riferimenti_circolari">Problema con <code>JSON.stringify()</code> durante la serializzazione di riferimenti circolari</h3> - -<p>Nota che poiché il <a href="https://www.json.org/">Formato JSON</a> non supporta i riferimenti agli oggetti (sebbene <a href="http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03">esista una bozza IETF</a>), {{JSxRef("TypeError")}} verrà generato un se si tenta di codificare un oggetto con riferimenti circolari.</p> - -<pre class="brush: js example-bad">const circularReference = {}; -circularReference.myself = circularReference; - -// La serializzazione dei riferimenti circolari genera "TypeError: valore dell'oggetto ciclico" -JSON.stringify(circularReference); -</pre> - -<p>Per serializzare i riferimenti circolari è possibile utilizzare una libreria che li supporta (ad es. <a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js">cycle.js</a> di Douglas Crockford) o implementare una soluzione autonomamente, che richiederà la ricerca e la sostituzione (o la rimozione) dei riferimenti ciclici mediante valori serializzabili.</p> - -<h3 id="Problema_con_plain_JSON.stringify_per_l'uso_come_JavaScript"><font><font>Problema con plain </font></font> <code>JSON.stringify</code> per l'uso come JavaScript</h3> - -<p>Storicamente, JSON <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">non era un sottoinsieme completamente rigido di JavaScript</a>. <font>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. </font><font>Ma non potevano apparire letteralmente in un contesto simile nel testo JavaScript - solo usando escape Unicode come</font> <code>\u2028</code> e <code>\u2029</code>. Questo è cambiato di recente: ora entrambi i punti di codice possono apparire letteralmente nelle stringhe in JSON e JavaScript entrambi.</p> - -<p><font><font>Pertanto, se è richiesta la compatibilità con i motori JavaScript precedenti, è pericoloso sostituire direttamente la stringa restituita da </font></font><code>JSON.stringify</code> <font><font>una stringa JavaScript da passare a </font></font><code>eval</code> <font><font>o </font></font><code>new Function</code> <font><font>o come parte di un </font><font>URL </font></font><a href="https://en.wikipedia.org/wiki/JSONP" rel="noopener"><font><font>JSONP</font></font></a><font><font> e può essere utilizzata la seguente utility:</font></font></p> - -<pre class="brush: js">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"} -</pre> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: N<font>on è garantito che le proprietà degli oggetti non array vengano sottoposte a stringa in qualsiasi ordine particolare. </font><font>Non fare affidamento sull'ordinamento di proprietà all'interno dello stesso oggetto all'interno della stringa.</font></p> -</div> - -<pre class="brush: js">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 -</pre> - -<h3 id="Esempio_di_utilizzo_JSON.stringify()_con_localStorage">Esempio di utilizzo <code>JSON.stringify()</code> con <code>localStorage</code></h3> - -<p><font><font>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 </font></font><code>JSON.stringify()</code><font><font>:</font></font></p> - -<pre class="brush: js">// 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); -</pre> - -<h3 id="Well-formed_JSON.stringify()">Well-formed <code>JSON.stringify()</code></h3> - -<p>Engines implementing the <a href="https://github.com/tc39/proposal-well-formed-stringify">well-formed JSON.stringify specification</a> will stringify lone surrogates -- any code point from U+D800 to U+DFFF -- using Unicode escape sequences rather than literally. Before this change <code>JSON.stringify</code> would output lone surrogates if the input contained any lone surrogates; such strings could not be encoded in valid UTF-8 or UTF-16:</p> - -<pre class="brush: js; no-line-numbers">JSON.stringify("\uD800"); // '"�"'</pre> - -<p><font><font>Ma con questo cambiamento </font></font><code>JSON.stringify</code> <font><font>rappresentano surrogati solitari usando sequenze di escape JSON che </font></font><em><font><font>possono</font></font></em><font><font> essere codificate in UTF-8 o UTF-16 validi:</font></font></p> - -<pre class="brush: js; no-line-numbers">JSON.stringify("\uD800"); // '"\\ud800"'</pre> - -<p><font><font>Questo cambiamento dovrebbe essere retrocompatibile fin tanto che si passa il risultato di </font></font><code>JSON.stringify</code> <font><font>API come </font></font><code>JSON.parse</code> <font><font>quella che accetterà qualsiasi testo JSON valido, in quanto tratterà le escape Unicode dei surrogati soli come identici ai surrogati solitari stessi. </font></font><em><font><font>Solo</font></font></em><font><font> se stai interpretando direttamente il risultato di </font></font><code>JSON.stringify</code> <font><font>hai bisogno di gestire attentamente </font></font><code>JSON.stringify</code> <font><font>le due possibili codifiche di questi punti di codice.</font></font></p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definzione iniziale. Implementato su JavaScript 1.7.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatiblità_con_i_browser">Compatiblità con i browser</h2> - -<div> - - -<p>{{Compat("javascript.builtins.JSON.stringify")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{JSxRef("JSON.parse()")}}</li> - <li><a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js">cycle.js</a> – Presenta due funzioni: <code>JSON.decycle</code> e <code>JSON.retrocycle</code>. Esse consentono la codifica e la decodifica di strutture cicliche e DAG in un formato JSON esteso e retrocompatibile.</li> -</ul> 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 deleted file mode 100644 index 85918279ad..0000000000 --- a/files/it/web/javascript/reference/global_objects/map/clear/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>clear()</strong></code> rimuove tutti gli elementi di un oggetto <code>Map</code>.</p> - -<div>{{EmbedInteractiveExample("pages/js/map-prototype-clear.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><em>myMap</em>.clear();</code></pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>{{jsxref("undefined")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzare_il_metodo_clear">Utilizzare il metodo <code>clear</code></h3> - -<pre class="brush: js">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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-map.prototype.clear', 'Map.prototype.clear')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser</h2> - - - -<p>{{Compat("javascript.builtins.Map.clear")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Map")}}</li> -</ul> 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 deleted file mode 100644 index 18c511b3eb..0000000000 --- a/files/it/web/javascript/reference/global_objects/map/delete/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: Map.prototype.delete() -slug: Web/JavaScript/Reference/Global_Objects/Map/delete -translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete ---- -<div>{{JSRef}}</div> - -<p><code>Il metodo</code><strong><code>delete()</code></strong> rimuove l'elemento specificato da un oggetto <code>Map</code> selezionandolo in base alla chiave.</p> - -<div>{{EmbedInteractiveExample("pages/js/map-prototype-delete.html")}}</div> - -<p class="hidden">Il codice sorgente per questo esempio interattivo è contenuto in un repository GitHub. Nel caso in cui tu voglia contribuire al progetto esempi interattivi, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e sottometti una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>myMap</var>.delete(<var>key</var>);</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>key</code></dt> - <dd>La chiave dell'elemento da rimuovere dall'oggetto <code>Map</code>.</dd> -</dl> - -<h3 id="Valore_ritornato">Valore ritornato</h3> - -<p><code>true</code> se un elemento con la chiave specificata esisteva nell'oggetto <code>Map</code> ed è stato ora rimosso, o <code>false</code> se non esisteva alcun elemento con la chiave specificata.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_delete">Usare <code>delete()</code></h3> - -<pre class="brush: js">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. -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-map.prototype.delete', 'Map.prototype.delete')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div class="hidden">La tabella di compatibilità contenuta in questa pagina è generata da dati strutturati. Per contribuire ai dati fai il check out del repository <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e sottometti una pull request.</div> - -<p>{{Compat("javascript.builtins.Map.delete")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Map")}}</li> -</ul> 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 deleted file mode 100644 index ab1c69a310..0000000000 --- a/files/it/web/javascript/reference/global_objects/map/foreach/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>forEach() </strong></code>esegue una funzione fornita come argomento una volta per ogni coppia <code>key/value</code> nell'oggetto <code>Map</code>, secondo l'ordine dell'inseriemento dei valori.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><em>myMap</em>.forEach(<em>callback</em>[, <em>thisArg</em>])</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Funzione da eseguire per ogni elemento.</dd> - <dt><code>thisArg</code></dt> - <dd>Valore da usare come <code>this</code> quando si esegue <code>callback</code>.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>forEach</code> esegue il <code>callback</code> passato come parametro una volta per ogni <em>key</em> della <em>map</em> esistente. Non è invocato per <em>key</em> che sono state cancellate. Comunque, è invocato per valori che sono presenti ma hanno valore <code>undefined</code>.</p> - -<p><code>callback </code>è invocato con <strong>tre argomenti</strong><code>:</code></p> - -<ul> - <li>il <strong>valore</strong> dell'<strong>elemento</strong></li> - <li>la <strong>chiave</strong> dell'<strong>elemento</strong></li> - <li>l'oggetto <strong><code>Map</code> </strong>su cui si sta eseguendo il ciclo</li> -</ul> - -<p>Se il parametro <code>thisArg</code> è fornito al <code>forEach</code>, sarà passato al <code>callback</code> quando viene invocato, per essere usato come suo valore <code>this</code>. In caso contrario, sarà passato il valore <code>undefined</code> per essere usato come valore <code>this</code>. Il valore <code>this </code>visibile definitivamente dal <code>callback</code>è determinato secondo le <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">normali regole per determinare il this visibile da una funzione</a>.</p> - -<p>Il range di elementi processati da <code>forEach</code> è determinato anteriormente alla prima invocazione del <code>callback</code>. Gli elementi che sono aggiunti all'oggetto <code>Map</code> dopo che la chiamata a <code>forEach</code> inizi non saranno visitati dal <code>callback</code>. Se eleemnti esistenti dell'oggetto <code>Map</code> vengono cambiati, o cancellati, il loro valore passato al <code>callback</code> sarà il valore nel momento in cui il <code>forEach</code> li visita; elementi che vengono cancellati non sono visitati.</p> - -<p><code>forEach</code> esegue la funzione <code>callback</code> una volta per ogni elemento nell'oggetto <code>Map</code>; non restituisce alcun valore.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Stampare_il_contenuto_di_un_oggetto_Map"><code>Stampare il contenuto di un oggetto Map</code></h3> - -<p>Il seguente codice stampa nella console una riga per ogni elemento in un oggetto<code> Map</code>:</p> - -<pre class="brush:js">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" -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Definizione iniziale.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_dei_browser">Compatibilità dei browser</h2> - -<p>{{Compat("javascript.builtins.Map.forEach")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.forEach()")}}</li> - <li>{{jsxref("Set.prototype.forEach()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/map/index.html b/files/it/web/javascript/reference/global_objects/map/index.html deleted file mode 100644 index 58ee676d23..0000000000 --- a/files/it/web/javascript/reference/global_objects/map/index.html +++ /dev/null @@ -1,439 +0,0 @@ ---- -title: Map -slug: Web/JavaScript/Reference/Global_Objects/Map -tags: - - ECMAScript6 - - Experimental - - JavaScript - - Map - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Map ---- -<div>{{JSRef}}</div> - -<p>The <strong><code>Map</code></strong> 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.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><code>new Map([iterable]) -</code></pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>iterable</code></dt> - <dd>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. <code>null</code> is treated as <code>undefined</code>.</dd> -</dl> - -<h2 id="Description">Description</h2> - -<p>A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of <code>[key, value]</code> for each iteration.</p> - -<h3 id="Key_equality">Key equality</h3> - -<p>Key equality is based on the "same-value" algorithm: <code>NaN</code> is considered the same as <code>NaN</code> (even though <code>NaN !== NaN</code>) and all other values are considered equal according to the semantics of the === operator. In earlier versions of the ECMAScript 6 draft <code>-0</code> and <code>+0</code> were considered distinct (even though <code>-0 === +0</code>), this has been changed in later versions and has been adapted in Gecko 29 {{geckoRelease("29")}} ({{bug("952870")}}) and a <a href="https://code.google.com/p/v8/issues/detail?id=3069">recent nightly Chrome</a>.</p> - -<h3 id="Objects_and_maps_compared">Objects and maps compared</h3> - -<p>{{jsxref("Object", "Objects")}} are similar to <code>Maps</code> 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), <code>Objects</code> have been used as <code>Maps</code> historically; however, there are important differences between <code>Objects</code> and <code>Maps</code> that make using a <code>Map</code> better:</p> - -<ul> - <li>An <code>Object</code> has a prototype, so there are default keys in the map. This could be bypassed by using <code>map = Object.create(null)</code> since ES5, but was seldomly done.</li> - <li>The keys of an <code>Object</code> are {{jsxref("String", "Strings")}} and {{jsxref("Symbol", "Symbols")}}, where they can be any value for a <code>Map</code>.</li> - <li>You can get the size of a <code>Map</code> easily while you have to manually keep track of size for an <code>Object</code>.</li> -</ul> - -<p>This does not mean you should use <code>Map</code>s everywhere, objects still are used in most cases. <code>Map</code> 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.<br> - If you're still not sure which one to use, ask yourself the following questions:</p> - -<ul> - <li>Are keys usually unknown until run time, do you need to look them up dynamically?</li> - <li>Do all values have the same type, and can be used interchangeably?</li> - <li>Do you need keys that aren't strings?</li> - <li>Are key-value pairs often added or removed?</li> - <li>Do you have an arbitrary (easily changing) amount of key-value pairs?</li> - <li>Is the collection iterated?</li> -</ul> - -<p>Those all are signs that you want a <code>Map</code> 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.</p> - -<h2 id="Properties">Properties</h2> - -<dl> - <dt><code>Map.length</code></dt> - <dd>The value of the <code>length</code> property is 0.</dd> - <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt> - <dd>The constructor function that is used to create derived objects.</dd> - <dt>{{jsxref("Map.prototype")}}</dt> - <dd>Represents the prototype for the <code>Map</code> constructor. Allows the addition of properties to all <code>Map</code> objects.</dd> -</dl> - -<h2 id="Map_instances"><code>Map</code> instances</h2> - -<p>All <code>Map</code> instances inherit from {{jsxref("Map.prototype")}}.</p> - -<h3 id="Properties_2">Properties</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}</p> - -<h3 id="Methods">Methods</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Using_the_Map_object">Using the <code>Map</code> object</h3> - -<pre class="brush: js">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 () {} -</pre> - -<h3 id="Using_NaN_as_Map_keys">Using <code>NaN</code> as <code>Map</code> keys</h3> - -<p><code>NaN</code> can also be used as a key. Even though every <code>NaN</code> is not equal to itself (<code>NaN !== NaN</code> is true), the following example works, because <code>NaN</code>s are indistinguishable from each other:</p> - -<pre class="brush: js">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" -</pre> - -<h3 id="Iterating_Maps_with_for..of">Iterating <code>Maps</code> with <code>for..of</code></h3> - -<p>Maps can be iterated using a <code>for..of</code> loop:</p> - -<pre class="brush: js">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" -</pre> - -<h3 id="Iterating_Maps_with_forEach()">Iterating <code>Maps</code> with <code>forEach()</code></h3> - -<p>Maps can be iterated using the <code>forEach()</code> method:</p> - -<pre class="brush: js">myMap.forEach(function(value, key) { - console.log(key + " = " + value); -}, myMap) -// Will show 2 logs; first with "0 = zero" and second with "1 = one" -</pre> - -<h3 id="Relation_with_Array_objects">Relation with <code>Array</code> objects</h3> - -<pre class="brush: js">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"] -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-map-objects', 'Map')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td> - <p>{{ CompatChrome(38) }} [1]</p> - </td> - <td>{{ CompatGeckoDesktop("13") }}</td> - <td>11</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td>Constructor argument: <code>new Map(iterable)</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>{{ CompatGeckoDesktop("13") }}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>iterable</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{ CompatGeckoDesktop("17") }}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Map.clear()</code></td> - <td>{{ CompatChrome(31) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("19")}}</td> - <td>11</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Map.keys(), Map.values(), Map.entries()</code></td> - <td>{{ CompatChrome(37) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("20")}}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Map.forEach()</code></td> - <td>{{ CompatChrome(36) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("25")}}</td> - <td>11</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td>Key equality for -0 and 0</td> - <td>{{ CompatChrome(34) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("29")}}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>Constructor argument: <code>new Map(null)</code></td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td>Monkey-patched <code>set()</code> in Constructor</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Map[@@species]</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoDesktop("41")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Map()</code> without <code>new</code> throws</td> - <td>{{CompatUnknown}}</td> - <td>{{ CompatGeckoDesktop("42") }}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }} [1]</td> - <td>{{ CompatGeckoMobile("13") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td>Constructor argument: <code>new Map(iterable)</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{ CompatGeckoMobile("13") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>iterable</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{ CompatGeckoMobile("17") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Map.clear()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(31) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("19")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Map.keys(), Map.values(), Map.entries()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(37) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("20")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Map.forEach()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(36) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("25")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td>Key equality for -0 and 0</td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(34) }}<br> - {{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("29")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>Constructor argument: <code>new Map(null)</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td>Monkey-patched <code>set()</code> in Constructor</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Map[@@species]</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("41")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Map()</code> without <code>new</code> throws</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("42")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Starting with Chrome 31, the feature was available behind a preference. In <code>chrome://flags</code>, activate the entry “Enable Experimental JavaScript”.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=697479">Map and Set bug at Mozilla</a></li> - <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets">ECMAScript Harmony proposal</a></li> - <li>{{jsxref("Set")}}</li> - <li>{{jsxref("WeakMap")}}</li> - <li>{{jsxref("WeakSet")}}</li> -</ul> 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 deleted file mode 100644 index 6dcf7a7dd6..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/abs/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Math.abs() -slug: Web/JavaScript/Reference/Global_Objects/Math/abs -translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.abs()</code></strong> ritorna il valore assoluto di un numero, ovvero</p> - -<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.abs</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mrow><mo stretchy="false">|</mo><mi>x</mi><mo stretchy="false">|</mo></mrow><mo>=</mo><mrow><mo>{</mo><mtable columnalign="left left"><mtr><mtd><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr><mtr><mtd><mi>0</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>=</mo><mn>0</mn></mtd></mtr><mtr><mtd><mo>-</mo><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr></mtable></mrow></mrow><annotation encoding="TeX">{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases} </annotation></semantics></math></p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">Math.abs(<var>x</var>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>x</code></dt> - <dd>Un numero.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Il valore assoluto del numero passato come parametro.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Siccome <code>abs()</code> è un metodo statico di <code>Math</code>, viene sempre utilizzato come <code>Math.abs()</code> piuttosto che come metodo di un oggetto <code>Math</code> creato in precedenza (<code>Math</code> non è un costruttore).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Comportamento_di_Math.abs()">Comportamento di <code>Math.abs()</code></h3> - -<p>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.</p> - -<pre class="brush: js" dir="rtl">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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_Browser">Compatibilità con i Browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.abs")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.ceil()")}}</li> - <li>{{jsxref("Math.floor()")}}</li> - <li>{{jsxref("Math.round()")}}</li> - <li>{{jsxref("Math.sign()")}}</li> - <li>{{jsxref("Math.trunc()")}}</li> -</ul> 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 deleted file mode 100644 index b872e04ab2..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/acos/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Math.acos() -slug: Web/JavaScript/Reference/Global_Objects/Math/acos -translation_of: Web/JavaScript/Reference/Global_Objects/Math/acos ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.acos()</code></strong> ritorna l'arcocoseno (in radianti) di un numero, ovvero</p> - -<p><math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>∊</mo><mo stretchy="false">[</mo><mrow><mo>-</mo><mn>1</mn></mrow><mo>;</mo><mn>1</mn><mo stretchy="false">]</mo><mo>,</mo><mspace width="thickmathspace"></mspace><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.acos</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mo lspace="0em" rspace="0em">arccos</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext> the unique </mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mo>∊</mo><mo stretchy="false">[</mo><mn>0</mn><mo>;</mo><mi>π</mi><mo stretchy="false">]</mo><mspace width="thinmathspace"></mspace><mtext>such that</mtext><mspace width="thickmathspace"></mspace><mo lspace="0em" rspace="0em">cos</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\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</annotation></semantics></math></p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.acos(<var>x</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>x</code></dt> - <dd>Un numero.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'arcocoseno (in radianti) del numero passato come parametro se quest'ultimo si trova tra i valori <strong>-1</strong> e <strong>1</strong>; altrimenti ritorna {{jsxref("NaN")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>Math.acos()</code> ritorna un valore numerico compreso tra 0 and π radianti per <code>x</code> compreso tra -1 e 1. Se il valore di <code>x</code> si trova al di fuori di questo range il metodo ritorna {{jsxref("NaN")}}.</p> - -<p>Siccome <code>acos()</code> è un metodo statico di <code>Math</code>, viene sempre usato come <code>Math.acos()</code> piuttosto che come metodo di un oggetto <code>Math</code> creato in precedenza (<code>Math</code> non è un costruttore).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Math.acos()"><code>Math.acos()</code></h3> - -<pre class="brush: js">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 -</pre> - -<p>Per valori inferiori a -1 o maggiori di 1, <code>Math.acos()</code> ritorna {{jsxref("NaN")}}.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.2', 'Math.acos')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.acos', 'Math.acos')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.acos', 'Math.acos')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_dei_Browser">Compatibilità dei Browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.acos")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.asin()")}}</li> - <li>{{jsxref("Math.atan()")}}</li> - <li>{{jsxref("Math.atan2()")}}</li> - <li>{{jsxref("Math.cos()")}}</li> - <li>{{jsxref("Math.sin()")}}</li> - <li>{{jsxref("Math.tan()")}}</li> -</ul> 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 deleted file mode 100644 index 9be8920214..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/atan/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Math.atan() -slug: Web/JavaScript/Reference/Global_Objects/Math/atan -translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.atan()</code></strong> restituisce l'arcotangente (in radianti) di un numero, definita come</p> - -<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.atan</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mo lspace="0em" rspace="0em">arctan</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext> l'unica </mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mo>∊</mo><mrow><mo>[</mo><mrow><mo>-</mo><mfrac><mi>π</mi><mn>2</mn></mfrac><mo>;</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><mo>]</mo></mrow><mspace width="thinmathspace"></mspace><mtext>tale che</mtext><mspace width="thickmathspace"></mspace><mo lspace="0em" rspace="0em">tan</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\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</annotation></semantics></math></p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.atan(<var>x</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>x</code></dt> - <dd>Un numero.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'arcotangente (in radianti) del numero dato <strong><code>x</code></strong>.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>Math.atan()</code> ritorna un valore numerico compreso tra <math><semantics><mrow><mo>-</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><annotation encoding="TeX">-\frac{\pi}{2}</annotation></semantics></math> e <math><semantics><mfrac><mi>π</mi><mn>2</mn></mfrac><annotation encoding="TeX">\frac{\pi}{2}</annotation></semantics></math> radianti.</p> - -<p>Poiché <code>atan()</code> è un membro statico di <code>Math</code>, è da usarsi sempre nella forma <code>Math.atan()</code>, piuttosto che come un metodo di un oggetto <code>Math</code> creato (<code>Math</code> non è il costruttore di una classe).</p> - -<h2 id="Esempî">Esempî</h2> - -<h3 id="Using_Math.atan()">Using <code>Math.atan()</code></h3> - -<pre class="brush: js">Math.atan(1); // 0.7853981633974483 -Math.atan(0); // 0 -Math.atan(-0); // -0 - -Math.atan(Infinity); <span class="objectBox objectBox-number"> // 1.5707963267948966 -Math.atan(-Infinity); // -1.5707963267948966 - -</span>/* -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); -</pre> - -<p>Note that you may want to avoid using <strong>±</strong><code>Infinity</code> for stylistic reasons. In this case, {{jsxref("Math.atan2()")}} with <code>0</code> as the second argument may be a better solution.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Status</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.4', 'Math.atan')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.atan', 'Math.atan')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.atan', 'Math.atan')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.atan")}}</p> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Math.acos()")}}</li> - <li>{{jsxref("Math.asin()")}}</li> - <li>{{jsxref("Math.atan2()")}}</li> - <li>{{jsxref("Math.cos()")}}</li> - <li>{{jsxref("Math.sin()")}}</li> - <li>{{jsxref("Math.tan()")}}</li> -</ul> 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 deleted file mode 100644 index 842106f7a1..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/atan2/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.atan2() </code></strong>restituisce l'arcotangente del quoziente dei suoi argomenti.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.atan2(<var>y</var>, <var>x</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>y</code></dt> - <dd>Primo numero.</dd> - <dt><code>x</code></dt> - <dd>Secondo numero.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>L'arcotangente del quoziente degli argomenti forniti alla funzione, espresso in radianti e compreso tra -π e π.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>Math.atan2()</code> restituisce un valore compreso tra -π e π che reppresenta l'angolo teta di un punto <code>(x, y)</code>. Questo angolo è orientato in senso antiorario, misurato in radianti e compreso tra l'asse positivo delle ascisse, ed il punto <code>(x, y)</code>. È importante ricordare che il primo argomento da fornire alla funzione è l'ordinata del punto ed il secondo la sua ascissa.</p> - -<p><img alt="A simple diagram showing the angle returned by atan2(y, x)" src="https://mdn.mozillademos.org/files/11557/atan2.png" style="height: 300px; width: 300px;"></p> - -<p><code>A Math.atan2()</code> vengono passate x ed y separatamente, mentre a <code>Math.atan()</code> deve essere passato il loro quoziente.</p> - -<p>Poichè <code>atan2()</code> è un metodo statico di <code>Math </code>esso viene sempre utilizzato nella forma <code>Math.atan2()</code>, invece che come metodo di un oggetto <code>Math </code>che hai personalmente creato (<code>Math</code> non è un costruttore).</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Using_Math.atan2()">Using <code>Math.atan2()</code></h3> - -<pre class="brush: js">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. -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.5', 'Math.atan2')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.atan2', 'Math.atan2')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.atan2', 'Math.atan2')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Math.acos()")}}</li> - <li>{{jsxref("Math.asin()")}}</li> - <li>{{jsxref("Math.atan()")}}</li> - <li>{{jsxref("Math.cos()")}}</li> - <li>{{jsxref("Math.sin()")}}</li> - <li>{{jsxref("Math.tan()")}}</li> -</ul> 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 deleted file mode 100644 index c8cdcb96dd..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/ceil/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Math.ceil() -slug: Web/JavaScript/Reference/Global_Objects/Math/ceil -translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.ceil()</code></strong> ritorna il più piccolo intero più grande di o uguale a un dato numero.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.ceil(<var>x</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>x</code></dt> - <dd>Un numero.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Il più piccolo intero più grande di o uguale al dato numero.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Visto che <code>ceil()</code> è un metodo statico di <code>Math</code>, va usato sempre come <code>Math.ceil()</code>, piuttosto che come metodo di un oggetto <code>Math</code> creato (<code>Math</code> non è un costruttore).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_Math.ceil()">Usare <code>Math.ceil()</code></h3> - -<p>L'esempio seguente mostra un uso di <code>Math.ceil()</code>.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="Arrotondamento_decimale">Arrotondamento decimale</h3> - -<pre class="brush: js">// 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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_dei_browser">Compatibilità dei browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.ceil")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.abs()")}}</li> - <li>{{jsxref("Math.floor()")}}</li> - <li>{{jsxref("Math.round()")}}</li> - <li>{{jsxref("Math.sign()")}}</li> - <li>{{jsxref("Math.trunc()")}}</li> -</ul> 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 deleted file mode 100644 index 859d16145b..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/e/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Math.E -slug: Web/JavaScript/Reference/Global_Objects/Math/E -translation_of: Web/JavaScript/Reference/Global_Objects/Math/E ---- -<div>{{JSRef}}</div> - -<p>La costante <strong><code>Math.E</code></strong> rappresenta la base del logaritmo naturale, e, equivale approssimativamente a 2.718.</p> - -<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.E</mi></mstyle><mo>=</mo><mi>e</mi><mo>≈</mo><mn>2.718</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.E}} = e \approx 2.718</annotation></semantics></math></p> - -<div>{{EmbedInteractiveExample("pages/js/math-e.html")}}</div> - - - -<div>{{js_property_attributes(0, 0, 0)}}</div> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Poiché <code>E</code> è una proprietà statica di <code>Math</code>, lo si usa sempre come <code>Math.E</code>, piuttosto che come un metodo di un <code>Oggetto Math</code> appositamente creato (<code>Math</code> non ha un costruttore).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Uso_di_Math.E"><code><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="background-color: #333333;">Uso di </span></font>Math.E</code></h3> - -<p>Il codice seguente restitusice e:</p> - -<pre class="brush: js">function getNapier() { - return Math.E; -} - -getNapier(); // 2.718281828459045 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.e', 'Math.E')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.E")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.exp()")}}</li> - <li>{{jsxref("Math.log()")}}</li> - <li>{{jsxref("Math.log1p()")}}</li> -</ul> 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 deleted file mode 100644 index 3f7f6c7851..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/floor/index.html +++ /dev/null @@ -1,158 +0,0 @@ ---- -title: Math.floor() -slug: Web/JavaScript/Reference/Global_Objects/Math/floor -translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.floor()</code></strong> restituisce il numero intero, arrotondato per difetto, del numero passato come parametro.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.floor(<var>x</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>x</code></dt> - <dd>Un numero.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero intero rappresentante l'arrotondamento per difetto del numero passato come parametro.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Siccome <code>floor()</code> è un metodo statico di <code>Math</code>, viene sempre usato come <code>Math.floor()</code> piuttosto che come metodo di un oggetto <code>Math</code> creato in precedenza (<code>Math</code> non è un costruttore).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Math.floor()"><code>Math.floor()</code></h3> - -<pre class="brush: js">Math.floor( 45.95); // 45 -Math.floor( 45.05); // 45 -Math.floor( 4 ); // 4 -Math.floor(-45.05); // -46 -Math.floor(-45.95); // -46 -</pre> - -<h3 id="Arrotondamento_decimale">Arrotondamento decimale</h3> - -<pre class="brush: js">// 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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_dei_Browser">Compatibilità dei Browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.floor")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.abs()")}}</li> - <li>{{jsxref("Math.ceil()")}}</li> - <li>{{jsxref("Math.round()")}}</li> - <li>{{jsxref("Math.sign()")}}</li> - <li>{{jsxref("Math.trunc()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/math/index.html b/files/it/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index 69cd2ec012..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -<div>{{JSRef}}</div> - -<p>Math è un oggetto precostruito che possiede proprietà e metodi per restituire i risultati di costanti e funzioni matematiche. Math non è una funzione.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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.</p> - -<h2 id="Proprietà">Proprietà</h2> - -<dl> - <dt>{{jsxref("Math.E")}}</dt> - <dd>Costante di Eulero e base dei logaritmi naturali, approssimativamente 2.718.</dd> - <dt>{{jsxref("Math.LN2")}}</dt> - <dd>Logaritmo naturale di 2, approssimativamente 0.693.</dd> - <dt>{{jsxref("Math.LN10")}}</dt> - <dd>Logaritmo naturale di 10, approssimativamente 0.693.</dd> - <dt>{{jsxref("Math.LOG2E")}}</dt> - <dd>Logaritmo a base 2 di E, approssimativamente 1.443.</dd> - <dt>{{jsxref("Math.LOG10E")}}</dt> - <dd>Logaritmo a base 10 di E, approssimativamente 1.443.</dd> - <dt>{{jsxref("Math.PI")}}</dt> - <dd>Rapporto tra la circonferenza di un cerchio ed il suo diametro, approssimativamente 3.14159.</dd> - <dt>{{jsxref("Math.SQRT1_2")}}</dt> - <dd>Radice quadrata di 1/2 ; equivale a 1 fratto la radice quadrata di 2, approsimativamente 0.707.</dd> - <dt>{{jsxref("Math.SQRT2")}}</dt> - <dd>Radice quadrata di 2, approssimativamente 1.414.</dd> -</dl> - -<h2 id="Metodi">Metodi</h2> - -<div class="note"> -<p>Ricorda che le funzioni trigonometriche (<code>sin()</code>, <code>cos()</code>, <code>tan()</code>, <code>asin()</code>, <code>acos()</code>, <code>atan()</code>, <code>atan2()</code>) si aspettano e restituiscono gli angoli in radianti. To convert radians to degrees, divide by <code>(Math.PI / 180)</code>, and multiply by this to convert the other way.</p> -</div> - -<div class="note"> -<p>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.</p> -</div> - -<dl> - <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}</dt> - <dd>Returns the absolute value of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}</dt> - <dd>Returns the arccosine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}</dt> - <dd>Returns the hyperbolic arccosine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}</dt> - <dd>Returns the arcsine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}</dt> - <dd>Returns the hyperbolic arcsine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}</dt> - <dd>Returns the arctangent of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}</dt> - <dd>Returns the hyperbolic arctangent of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}</dt> - <dd>Returns the arctangent of the quotient of its arguments.</dd> - <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}</dt> - <dd>Returns the cube root of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}</dt> - <dd>Returns the smallest integer greater than or equal to a number.</dd> - <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}</dt> - <dd>Returns the number of leading zeroes of a 32-bit integer.</dd> - <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}</dt> - <dd>Returns the cosine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}</dt> - <dd>Returns the hyperbolic cosine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}</dt> - <dd>Returns E<sup>x</sup>, where <var>x</var> is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.</dd> - <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}</dt> - <dd>Returns subtracting 1 from <code>exp(x)</code>.</dd> - <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}</dt> - <dd>Returns the largest integer less than or equal to a number.</dd> - <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}</dt> - <dd>Returns the nearest <a href="http://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single precision">single precision</a> float representation of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}</dt> - <dd>Returns the square root of the sum of squares of its arguments.</dd> - <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}</dt> - <dd>Returns the result of a 32-bit integer multiplication.</dd> - <dt>{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}</dt> - <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}</dt> - <dd>Returns the natural logarithm of <code>1 + x</code> (log<sub>e</sub>, also ln) of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}</dt> - <dd>Returns the base 10 logarithm of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}</dt> - <dd>Returns the base 2 logarithm of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}</dt> - <dd>Returns the largest of zero or more numbers.</dd> - <dt>{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}</dt> - <dd>Returns the smallest of zero or more numbers.</dd> - <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}</dt> - <dd>Returns base to the exponent power, that is, <code>base<sup>exponent</sup></code>.</dd> - <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> - <dd>Returns a pseudo-random number between 0 and 1.</dd> - <dt>{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}</dt> - <dd>Returns the value of a number rounded to the nearest integer.</dd> - <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}</dt> - <dd>Returns the sign of the x, indicating whether x is positive, negative or zero.</dd> - <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}</dt> - <dd>Returns the sine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}</dt> - <dd>Returns the hyperbolic sine of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}</dt> - <dd>Returns the positive square root of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}</dt> - <dd>Returns the tangent of a number.</dd> - <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}</dt> - <dd>Returns the hyperbolic tangent of a number.</dd> - <dt><code>Math.toSource()</code> {{non-standard_inline}}</dt> - <dd>Returns the string <code>"Math"</code>.</dd> - <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}</dt> - <dd>Returns the integral part of the number x, removing any fractional digits.</dd> -</dl> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.1.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8', 'Math')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math-object', 'Math')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>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.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math-object', 'Math')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Number")}}</li> -</ul> 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 deleted file mode 100644 index 1c7f425fd0..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/max/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.max()</code></strong> restituisce il massimo tra zero o più numeri.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.max([<var>valore1</var>[, <var>valore2</var>[, ...]]])</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>valore1, valore2, ...</code></dt> - <dd>Numeri.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Dato che <code>max()</code> è un metodo statico di <code>Math</code>, viene solitamente usato tramite <code>Math.max()</code>, piuttosto che come metodo di un oggetto di tipo <code>Math</code> (<code>Math</code> non è un construttore).</p> - -<p>Se non vengono passati parametri, il risultato è -{{jsxref("Infinity")}}.</p> - -<p>Se anche solo uno dei parametri non può essere convertito a numero, il risultato è {{jsxref("NaN")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usando_Math.max()">Usando <code>Math.max()</code></h3> - -<pre class="brush: js">Math.max(10, 20); // 20 -Math.max(-10, -20); // -10 -Math.max(-10, 20); // 20 -</pre> - -<p>La seguente funzione usa il metodo {{jsxref("Function.prototype.apply()")}} per trovare l'elemento massimo in un array di numeri. <br> - <code>getMaxOfArray([1, 2, 3])</code> è equivalente a <code>Math.max(1, 2, 3)</code> ma può essere usata con array di qualunque dimensione creati programmaticamente.</p> - -<pre class="brush: js">function getMaxOfArray(numArray) { - return Math.max.apply(null, numArray); -} -</pre> - -<p>Con il nuovo {{jsxref("Operators/Spread_operator", "spread operator")}}, ottenere l'elemento massimo di un array è ancora più semplice.</p> - -<pre class="brush: js">var arr = [1, 2, 3]; -var max = Math.max(...arr); -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementata in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.max', 'Math.max')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_inoltre">Vedi inoltre</h2> - -<ul> - <li>{{jsxref("Math.min()")}}</li> -</ul> 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 deleted file mode 100644 index 562292e15b..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/min/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -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 ---- -<p> </p> - -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.min()</code></strong> ritorna il più piccolo tra zero o più numeri.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.min([<var>value1</var>[, <var>value2</var>[, ...]]])</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>value1, value2, ...</code></dt> - <dd>numeri.</dd> -</dl> - -<h3 id="Valori_di_Ritorno">Valori di Ritorno</h3> - -<p>Il più piccolo dei valori dati in input. Se uno degli argomenti non può essere convertito in numero, viene ritornato {{jsxref("NaN")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Siccome <code>min()</code> è un metodo static di <code>Math</code> , lo si può sempre usare come <code>Math.min()</code>, piuttosto che come un metodo di un oggetto istanza di <code>Math</code> da te creato (<code>Math</code> non possiede costruttori).</p> - -<p>Se non sono dati argomenti allora il metodo restituirà {{jsxref("Infinity")}}.</p> - -<p>Se anche uno degli aromenti non può essere convertito in un numero, il risultato sarà {{jsxref("NaN")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usando_Math.min()">Usando <code>Math.min()</code></h3> - -<p>L'sempio di seguito assegna a <code>z</code> il valore minore tra <code>x</code> e <code>y</code>:</p> - -<pre class="brush: js">var x = 10, y = -20; -var z = Math.min(x, y); -</pre> - -<h3 id="Ritagliare_un_valore_con_Math.min()">Ritagliare un valore con <code>Math.min()</code></h3> - -<p><code>Math.min()</code> è spesso usato per limitare un valore in modo che sia sempre minore o uguale a un certo valore limite.<br> - Ad esempio il seguente codice</p> - -<pre class="brush: js">var x = f(foo); - -if (x > boundary) { - x = boundary; -} -</pre> - -<p>può essere scritto come</p> - -<pre class="brush: js">var x = Math.min(f(foo), boundary); -</pre> - -<p>{{jsxref("Math.max()")}} può essere similmente utilizzato per limitare il valore massimo.</p> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.min', 'Math.min')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.max()")}}</li> -</ul> 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 deleted file mode 100644 index 5db4139f6a..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/pow/index.html +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Math.pow() -slug: Web/JavaScript/Reference/Global_Objects/Math/pow -translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.pow() </code></strong>restituisce la potenza della base che si desidera moltiplicare per se stessa a seconda del valore dell'esponenete, cioè <code>base<sup>esponente</sup></code>.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.pow(<var>base</var>, <var>esponente</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>base</code></dt> - <dd>La basee del numero.</dd> - <dt><code>esponente</code></dt> - <dd>L'esponente usato per elevare la base.</dd> -</dl> - -<h3 id="Valore_di_Ritorno">Valore di Ritorno</h3> - -<p>Un numero che rappresenta la base elevata alla potenza dell'esponente.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code><font face="Open Sans, Arial, sans-serif">Siccome </font>pow()</code> è un metodo static di <code>Math</code>, lo usi sempre nella forma <code>Math.pow()</code>, piuttosto che come un metodo di un oggetto <code>Math</code> da te creato (<code>Math</code> non ha costruttori).</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usando_Math.pow()">Usando <code>Math.pow()</code></h3> - -<pre class="brush: js">// 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 -</pre> - -<h2 id="Specifiche_Tecniche">Specifiche Tecniche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazione</th> - <th scope="col">Status</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td> - <p>Definizione iniziale. Implementata in JavaScript 1.0.</p> - </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.13', 'Math.pow')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.pow', 'Math.pow')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.pow', 'Math.pow')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatiblità_Browser">Compatiblità Browser </h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.cbrt()")}}</li> - <li>{{jsxref("Math.exp()")}}</li> - <li>{{jsxref("Math.log()")}}</li> - <li>{{jsxref("Math.sqrt()")}}</li> - <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation" title="Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).">Exponentiation operator</a> {{experimental_inline}}</li> -</ul> 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 deleted file mode 100644 index 3fcd849257..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/random/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Math.random() -slug: Web/JavaScript/Reference/Global_Objects/Math/random -translation_of: Web/JavaScript/Reference/Global_Objects/Math/random ---- -<div>{{JSRef}}</div> - -<div>La funzione <strong><code>Math.random()</code></strong> 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.</div> - -<div> </div> - -<div class="note"> -<p><code>Math.random()</code> <em>non </em>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()")}}.</p> -</div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">Math.random()</pre> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero pseudo casuale in virgola mobile compreso tra 0 (incluso) e 1 (escluso).</p> - -<h2 id="Esempi">Esempi</h2> - -<p>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 2<sup>53 </sup>o più) è possibile, in casi estremamente rari, calcolare il limite superiore solitamente escluso.</p> - -<h3 id="Ottenere_un_numero_tra_0_1)">Ottenere un numero tra [0, 1)</h3> - -<pre class="brush: js">function getRandom() { - return Math.random(); -} -</pre> - -<h3 id="Ottenere_un_numero_random_tra_due_valori">Ottenere un numero random tra due valori</h3> - -<p>Questo esempio restituisce un numero random tra due valori specificati. Il valore non è minore di (e può essere uguale a) <code>min</code>, nè maggiore (e nè uguale) a <code>max.</code> </p> - -<pre class="brush: js">function getRandomArbitrary(min, max) { - return Math.random() * (max - min) + min; -} -</pre> - -<h3 id="Ottenere_un_intero_random_tra_due_valori">Ottenere un intero random tra due valori</h3> - -<p>Questo esempio restituisce un intero random tra due valori specificati. Il valore non è minore di <code>min</code> (oppure l'intero più grande di min se quest'ultimo non è un intero), nè maggiore (nè uguale) a <code>max.</code> </p> - -<pre class="brush: js">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 -} -</pre> - -<div class="note"> -<p>Si potrebbe utilizzare l'arrotondamento per ottenere questo, tuttavia così facendo i numeri casuali seguirebbero una distribuzione non uniforme, magari non accettabile.</p> -</div> - -<h3 id="Ottenere_un_intero_random_tra_due_valori_con_estremi_inclusi">Ottenere un intero random tra due valori con estremi inclusi</h3> - -<p>Le funzioni viste finora escludono sempre l'estremo superiore del range scelto. La funzione <code>getRandomIntInclusive() </code>descritta sotto permette di ottenere questo.</p> - -<pre class="brush: js">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 -}</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. JS 1.0 (solo per UNIX) / JS 1.1. (tutte le piattaforme)</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.14', 'Math.random')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.random', 'Math.random')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.random', 'Math.random')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.random")}}</p> - -<p class="countTop"> </p> 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 deleted file mode 100644 index 4b20fb4a42..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/round/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Math.round() -slug: Web/JavaScript/Reference/Global_Objects/Math/round -translation_of: Web/JavaScript/Reference/Global_Objects/Math/round ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.round()</code></strong> restituisce il valore di un numero approssimato all'intero ad esso più vicino.</p> - -<div>{{EmbedInteractiveExample("pages/js/math-round.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">Math.round(<var>x</var>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>x</code></dt> - <dd>Un numero.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Il valore del numero dato approssimato all'intero più vicino.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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 +∞. <strong>Si noti che questo è diverso da quanto accade nelle funzioni <code>round()</code> di molti altri linguaggi, che spesso invece approssimano questo caso all'intero successivo <em>più lontano da zero</em>, </strong>(dando un risultato diverso nel caso dei numeri negativi con una parte frazionale di esattamente 0.5).</p> - -<p>Poiché <code>round()</code> è un metodo statico di <code>Math</code>, lo si usa sempre come <code>Math.round()</code>, piuttosto che come un metodo di un <code>Oggetto Math</code> appositamente creato (<code>Math</code> non ha un costruttore).</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">Math.round( 20.49); // 20 -Math.round( 20.5 ); // 21 -Math.round( 42 ); // 42 -Math.round(-20.5 ); // -20 -Math.round(-20.51); // -21 -</pre> - -<p> </p> - -<h2 id="Specifications">Specifications</h2> - -<p> </p> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.round', 'Math.round')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.round', 'Math.round')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Math.round")}}</p> - -<p> </p> - -<h2 id="See_also">See also</h2> - -<p> </p> - -<ul> - <li>{{jsxref("Number.toPrecision()")}}</li> - <li>{{jsxref("Number.toFixed()")}}</li> - <li>{{jsxref("Math.abs()")}}</li> - <li>{{jsxref("Math.ceil()")}}</li> - <li>{{jsxref("Math.floor()")}}</li> - <li>{{jsxref("Math.sign()")}}</li> - <li>{{jsxref("Math.trunc()")}}</li> -</ul> 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 deleted file mode 100644 index 6daf577e02..0000000000 --- a/files/it/web/javascript/reference/global_objects/math/sqrt/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Math.sqrt() -slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt -translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt ---- -<div>{{JSRef}}</div> - -<p>La funzione <strong><code>Math.sqrt()</code></strong> ritorna la radice quadrata di un numero, cioè :</p> - -<p><math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>≥</mo><mn>0</mn><mo>,</mo><mstyle mathvariant="monospace"><mrow><mi>M</mi><mi>a</mi><mi>t</mi><mi>h</mi><mo>.</mo><mi>s</mi><mi>q</mi><mi>r</mi><mi>t</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><msqrt><mi>x</mi></msqrt><mo>=</mo><mtext>the unique</mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mo>≥</mo><mn>0</mn><mspace width="thickmathspace"></mspace><mtext>such that</mtext><mspace width="thickmathspace"></mspace><msup><mi>y</mi><mn>2</mn></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{l'unico} \; y \geq 0 \; \text{tale che} \; y^2 = x</annotation></semantics></math></p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Math.sqrt(<var>x</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>x</code></dt> - <dd>Un numero.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>La radice quadrata di un dato numero. Se il numero è negativo viene ritornato {{jsxref("NaN")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Se il segno di <code>x</code> è negativo, <code>Math.sqrt()</code> ritorna {{jsxref("NaN")}}.</p> - -<p>Siccome <code>sqrt()</code> è un metodo static di <code>Math</code>, puoi usarlo sempre come <code>Math.sqrt()</code>, piutttosto che come un metodo di un oggetto di tipo <code>Math</code> creato da te (<code>Math</code> non è un costruttore).</p> - -<h2 id="Esempio">Esempio</h2> - -<h3 id="Uso_di_Math.sqrt()">Uso di <code>Math.sqrt()</code></h3> - -<pre class="brush: js">Math.sqrt(9); // 3 -Math.sqrt(2); // 1.414213562373095 - -Math.sqrt(1); // 1 -Math.sqrt(0); // 0 -Math.sqrt(-1); // NaN -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale. Implementato per JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.8.2.17', 'Math.sqrt')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-math.sqrt', 'Math.sqrt')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-math.sqrt', 'Math.sqrt')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Math.cbrt()")}}</li> - <li>{{jsxref("Math.exp()")}}</li> - <li>{{jsxref("Math.log()")}}</li> - <li>{{jsxref("Math.pow()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/nan/index.html b/files/it/web/javascript/reference/global_objects/nan/index.html deleted file mode 100644 index 992f063e9d..0000000000 --- a/files/it/web/javascript/reference/global_objects/nan/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: NaN -slug: Web/JavaScript/Reference/Global_Objects/NaN -translation_of: Web/JavaScript/Reference/Global_Objects/NaN ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}</div> -</div> -</div> - -<h2 id="Sommario">Sommario</h2> - -<p>La proprietà globale <strong style="font-family: Consolas,Monaco,'Andale Mono',monospace;">NaN </strong>è un valore che rappresenta un non numero (Not-a-Number).</p> - -<p>{{js_property_attributes(0,0,0)}}</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>NaN</code></pre> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>Nan è una proprietà del <em>global object </em>e indica il fatto che un certo valore non è un numero legale/valido.</p> - -<p>Il valore iniziale di Nan è Not-A-Number — lo stesso valore che si può riscontrare accedendo a <span style="font-family: Consolas,Monaco,'Andale Mono',monospace;">Number.NaN. </span>Nei browser moderni NaN è una proprietà non configurabile e non scrivibile (read-only).</p> - -<p>NaN è restituito principalmente come valore di fallimento dalle funzioni "matematiche" come <span style="font-family: Consolas,Monaco,'Andale Mono',monospace;">Math.sqrt(-1) </span>oppure quando si prova ad eseguire il parseInt di una stringa che non contiene cifre numeriche come <span style="font-family: Consolas,Monaco,'Andale Mono',monospace;">parseInt("blabla")</span></p> - -<h3 id="Testare_il_valore_NaN">Testare il valore <code>NaN</code></h3> - -<p>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()")}}. </p> - -<pre class="brush: js">NaN === NaN; // false -Number.NaN === NaN; // false -isNaN(NaN); // true -isNaN(Number.NaN); // true -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Initial definition. Implemented in JavaScript 1.3</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.1.1', 'NaN')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità">Compatibilità</h2> - - - -<p>{{Compat("javascript.builtins.NaN")}}</p> - -<h2 id="See_also" name="See_also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Number.NaN")}}</li> - <li>{{jsxref("Number.isNaN()")}}</li> - <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/null/index.html b/files/it/web/javascript/reference/global_objects/null/index.html deleted file mode 100644 index 80ee3de685..0000000000 --- a/files/it/web/javascript/reference/global_objects/null/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: 'null' -slug: Web/JavaScript/Reference/Global_Objects/null -translation_of: Web/JavaScript/Reference/Global_Objects/null ---- -<div>{{jsSidebar("Objects")}}</div> - -<p>Il valore <code>null</code> rappresenta l'assenza intenzionale di qualsiasi valore dell'oggetto. È una delle {{Glossary("Primitive", "primitive values")}} di JavaScript.</p> - -<div>{{EmbedInteractiveExample("pages/js/globalprops-null.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">null</pre> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il valore <code>null</code> è scritto con un letterale: <code>null</code>. <code>null</code> non è un identificatore per una proprietà dell'oggetto globale, come {{jsxref("Global_Objects/undefined","undefined")}} può essere. Invece, <code>null</code> esprime una mancanza di identificazione, indicando che una variabile punta a nessun oggetto. Nelle API, <code>null</code> viene spesso recuperato in un punto in cui è possibile prevedere un oggetto ma nessun oggetto è rilevante.</p> - -<pre class="brush: js">// 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" -</pre> - -<h3 id="Differenze_tra_null_e_undefined">Differenze tra <code>null</code> e <code>undefined</code></h3> - -<p>Durante il controllo per <code>null</code> o <code>undefined</code>, attenti alle <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">differenze tra gli operatori equality (==) e identity (===)</a>, come il primo esegue la conversione del tipo.</p> - -<pre class="brush: js">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</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-null-value', 'null value')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-null-value', 'null value')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - - - -<p>{{Compat("javascript.builtins.null")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("undefined")}}</li> - <li>{{jsxref("NaN")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/number/index.html b/files/it/web/javascript/reference/global_objects/number/index.html deleted file mode 100644 index 39c8eb37d2..0000000000 --- a/files/it/web/javascript/reference/global_objects/number/index.html +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Number -slug: Web/JavaScript/Reference/Global_Objects/Number -translation_of: Web/JavaScript/Reference/Global_Objects/Number ---- -<ol> - <li>{{JSRef}}</li> -</ol> - -<div><strong><code>Number</code></strong> is a <a href="/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript">primitive wrapper object</a> used to represent and manipulate numbers like <code>37</code> or <code>-9.25</code>.</div> - -<div></div> - -<div></div> - -<p>The <strong><code>Number</code></strong> constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the<strong> </strong><strong><code>Number()</code> function</strong>.</p> - -<p>The JavaScript <strong>Number</strong> type is a <a href="https://en.wikipedia.org/wiki/Floating-point_arithmetic">double-precision 64-bit binary format IEEE 754</a> value, like <code>double</code> 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 <a href="https://en.wikipedia.org/wiki/Floating-point_arithmetic#Representable_numbers,_conversion_and_rounding">rounding</a>. The largest value a Number can hold is about 1.8×10<sup>308</sup>. Numbers beyond that are replaced with the special Number constant {{jsxref("Infinity")}}.</p> - -<p>A number literal like <code>37</code> 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. <code>37</code> is still a Number, not a BigInt.)</p> - -<dl> -</dl> - -<h2 id="Description">Description</h2> - -<p>When used as a function, <code>Number(value)</code> converts a string or other value to the Number type. If the value can't be converted, it returns {{jsxref("NaN")}}.</p> - -<h3 id="Literal_syntax">Literal syntax</h3> - -<pre class="brush: js notranslate">123 // one-hundred twenty-three -123.0 // same -123 === 123.0 // true</pre> - -<h3 id="Function_syntax">Function syntax</h3> - -<pre class="brush: js notranslate">Number('123') // returns the number 123 -Number('123') === 123 // true - -Number("unicorn") // NaN -Number(undefined) // NaN -</pre> - -<h2 id="Constructor">Constructor</h2> - -<dl> - <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number"><code>Number()</code></a></dt> - <dd>Creates a new <code>Number</code> value.</dd> -</dl> - -<h2 id="Static_properties">Static properties</h2> - -<dl> - <dt>{{jsxref("Number.EPSILON")}}</dt> - <dd>The smallest interval between two representable numbers.</dd> - <dt>{{jsxref("Number.MAX_SAFE_INTEGER")}}</dt> - <dd>The maximum safe integer in JavaScript (<code>2<sup>53</sup> - 1</code>).</dd> - <dt>{{jsxref("Number.MAX_VALUE")}}</dt> - <dd>The largest positive representable number.</dd> - <dt>{{jsxref("Number.MIN_SAFE_INTEGER")}}</dt> - <dd>The minimum safe integer in JavaScript (<code>-(2<sup>53</sup> - 1)</code>).</dd> - <dt>{{jsxref("Number.MIN_VALUE")}}</dt> - <dd>The smallest positive representable number—that is, the positive number closest to zero (without actually being zero).</dd> - <dt>{{jsxref("Number.NaN")}}</dt> - <dd>Special "<strong>N</strong>ot <strong>a</strong> <strong>N</strong>umber" value.</dd> - <dt>{{jsxref("Number.NEGATIVE_INFINITY")}}</dt> - <dd>Special value representing negative infinity. Returned on overflow.</dd> - <dt>{{jsxref("Number.POSITIVE_INFINITY")}}</dt> - <dd>Special value representing infinity. Returned on overflow.</dd> - <dt>{{jsxref("Number.prototype")}}</dt> - <dd>Allows the addition of properties to the <code>Number</code> object.</dd> -</dl> - -<h2 id="Static_methods">Static methods</h2> - -<dl> - <dt>{{jsxref("Number.isNaN()")}}</dt> - <dd>Determine whether the passed value is <code>NaN</code>.</dd> - <dt>{{jsxref("Number.isFinite()")}}</dt> - <dd>Determine whether the passed value is a finite number.</dd> - <dt>{{jsxref("Number.isInteger()")}}</dt> - <dd>Determine whether the passed value is an integer.</dd> - <dt>{{jsxref("Number.isSafeInteger()")}}</dt> - <dd>Determine whether the passed value is a safe integer (number between <code>-(2<sup>53</sup> - 1)</code> and <code>2<sup>53</sup> - 1</code>).</dd> - <dt>{{jsxref("Number.parseFloat()", "Number.parseFloat(<var>string</var>)")}}</dt> - <dd>This is the same as the global {{jsxref("parseFloat", "parseFloat()")}} function.</dd> - <dt>{{jsxref("Number.parseInt()", "Number.parseInt(<var>string</var>, [<var>radix</var>])")}}</dt> - <dd>This is the same as the global {{jsxref("parseInt", "parseInt()")}} function.</dd> -</dl> - -<h2 id="Instance_methods">Instance methods</h2> - -<dl> - <dt>{{jsxref("Number.prototype.toExponential()" ,"Number.prototype.toExponential(<var>fractionDigits</var>)")}}</dt> - <dd>Returns a string representing the number in exponential notation.</dd> - <dt>{{jsxref("Number.prototype.toFixed()", "Number.prototype.toFixed(<var>digits</var>)")}}</dt> - <dd>Returns a string representing the number in fixed-point notation.</dd> - <dt>{{jsxref("Number.prototype.toLocaleString()", "Number.prototype.toLocaleString([<var>locales</var> [, <var>options</var>]])")}}</dt> - <dd>Returns a string with a language sensitive representation of this number. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.</dd> - <dt>{{jsxref("Number.prototype.toPrecision()", "Number.prototype.toPrecision(<var>precision</var>)")}}</dt> - <dd>Returns a string representing the number to a specified precision in fixed-point or exponential notation.</dd> - <dt>{{jsxref("Number.prototype.toString()", "Number.prototype.toString([<var>radix</var>])")}}</dt> - <dd>Returns a string representing the specified object in the specified <var>radix</var> ("base"). Overrides the {{jsxref("Object.prototype.toString()")}} method.</dd> - <dt>{{jsxref("Number.prototype.valueOf()")}}</dt> - <dd>Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.</dd> -</dl> - -<h2 id="Examples">Examples</h2> - -<h3 id="Using_the_Number_object_to_assign_values_to_numeric_variables">Using the Number object to assign values to numeric variables</h3> - -<p>The following example uses the <code>Number</code> object's properties to assign values to several numeric variables:</p> - -<pre class="brush: js notranslate">const biggestNum = Number.MAX_VALUE -const smallestNum = Number.MIN_VALUE -const infiniteNum = Number.POSITIVE_INFINITY -const negInfiniteNum = Number.NEGATIVE_INFINITY -const notANum = Number.NaN -</pre> - -<h3 id="Integer_range_for_Number">Integer range for Number</h3> - -<p>The following example shows the minimum and maximum integer values that can be represented as <code>Number</code> object. (More details on this are described in the ECMAScript standard, chapter <em><a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">6.1.6 The Number Type</a>.</em>)</p> - -<pre class="brush: js notranslate">const biggestInt = Number.MAX_SAFE_INTEGER // (<code>2<sup>53</sup> - 1</code>) => 9007199254740991 -const smallestInt = Number.MIN_SAFE_INTEGER // -(<code>2<sup>53</sup> - 1</code>) => -9007199254740991</pre> - -<p>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 <code>Number</code> type.</p> - -<p>A possible workaround is to use {{jsxref("String")}} instead.</p> - -<p>Larger numbers can be represented using the {{jsxref("BigInt")}} type.</p> - -<h3 id="Using_Number_to_convert_a_Date_object">Using Number to convert a Date object</h3> - -<p>The following example converts the {{jsxref("Date")}} object to a numerical value using <code>Number</code> as a function:</p> - -<pre class="brush: js notranslate">let d = new Date('December 17, 1995 03:24:00') -console.log(Number(d)) -</pre> - -<p>This logs <code>819199440000</code>.</p> - -<h3 id="Convert_numeric_strings_and_null_to_numbers">Convert numeric strings and null to numbers</h3> - -<pre class="brush: js notranslate" dir="rtl">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</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> - -<p>{{Compat("javascript.builtins.Number")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("NaN")}}</li> - <li>{{jsxref("Arithmetic operators")}}</li> - <li>The {{jsxref("Math")}} global object</li> - <li>Integers with arbitrary precision: {{jsxref("BigInt")}}</li> -</ul> 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 deleted file mode 100644 index 6280745df2..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/assign/index.html +++ /dev/null @@ -1,268 +0,0 @@ ---- -title: Object.assign() -slug: Web/JavaScript/Reference/Global_Objects/Object/assign -translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign ---- -<div>{{JSRef}}</div> - -<h2 id="Sommario">Sommario</h2> - -<p>La funzione <strong><code>Object.assign()</code></strong> copia tutte le proprietà enumerabili da uno o più oggetti di origine in un oggetto di destinazione. Restituisce l'oggetto di destinazione.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox notranslate"><code>Object.assign(<var>target</var>, ...<var>sources</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>target</code></dt> - <dd>L'oggetto di destinazione.</dd> - <dt><code>sources</code></dt> - <dd>Gli oggetti di origine.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>La funzione <code>Object.assign()</code> copia soltanto le proprietà <em>enumerabili</em> appartenenti agli oggetti di origine (non quelle che fanno parte della loro catena dei prototipi) in un oggetto di destinazione. Utilizza <code>[[Get]]</code> sugli oggetti di origine e <code>[[Put]]</code> su quello di destinazione, quindi invoca <em>getter</em> e <em>setter</em>, quando presenti. Quindi <em>assegna</em> 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 <em>getter</em> o <em>setter</em>. Per copiare le proprietà, incluso il fatto di essere enumerabili o no, in un prototipo, bisognerebbe usare {{jsxref("Object.defineProperty()")}}.</p> - -<p>Vengono copiate sia le proprietà aventi come nomi delle {{jsxref("String", "stringhe")}} che dei {{jsxref("Symbol", "simboli")}}.</p> - -<p>In caso di errore, per esempio se una proprietà non è sovrascrivibile, viene generato un {{jsxref("TypeError")}}, e l'oggetto di destinazione rimane invariato.</p> - -<p>Notare che <code>Object.assign()</code> non genera un errore se uno dei valori di origine è {{jsxref("null")}} o {{jsxref("undefined")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Clonare_un_oggetto">Clonare un oggetto</h3> - -<p>Si potrebbe pensare di clonare un oggetto semplicemente assegnandolo ad un altra variabile:</p> - -<pre class="brush: js notranslate">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?</pre> - -<p>Utilizzando <code>Object.assign()</code> il problema non si verifica:</p> - -<pre class="brush: js notranslate">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 } -</pre> - -<h3 id="Unire_più_oggetti">Unire più oggetti</h3> - -<pre class="brush: js notranslate">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 -</pre> - -<h3 id="Copiare_proprietà_aventi_come_indici_dei_simboli">Copiare proprietà aventi come indici dei simboli</h3> - -<pre class="brush: js notranslate">var o1 = { a: 1 }; -var o2 = { [Symbol("foo")]: 2 }; - -var obj = Object.assign({}, o1, o2); -console.log(obj); // { a: 1, Symbol(foo): 2 } -</pre> - -<h3 id="Le_proprietà_ereditate_o_non-enumerabili_non_vengono_copiate">Le proprietà ereditate o non-enumerabili non vengono copiate</h3> - -<pre class="brush: js notranslate">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 } -</pre> - -<h3 id="I_valori_primitivi_vengono_trasformati_in_oggetti">I valori primitivi vengono trasformati in oggetti</h3> - -<pre class="brush: js notranslate">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" } -</pre> - -<h3 id="Se_viene_generata_un_eccezione_la_funzione_si_ferma">Se viene generata un eccezione, la funzione si ferma</h3> - -<pre class="brush: js notranslate">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 -</pre> - -<h3 id="Copiare_i_getter">Copiare i getter</h3> - -<pre class="brush: js notranslate">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 } } -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>Questo polyfill non supporta i simboli (che comunque non sono supportati da ECMAScript 5):</p> - -<pre class="brush: js notranslate">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; - } - }); -} -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Edge</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{CompatChrome("45")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("34")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatOpera("32")}}</td> - <td>{{CompatSafari("9")}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: open sans light,sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Edge</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome("45")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("34")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Object.defineProperties()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/object/constructor/index.html b/files/it/web/javascript/reference/global_objects/object/constructor/index.html deleted file mode 100644 index 6a9c339acb..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/constructor/index.html +++ /dev/null @@ -1,222 +0,0 @@ ---- -title: Object.prototype.constructor -slug: Web/JavaScript/Reference/Global_Objects/Object/constructor -translation_of: Web/JavaScript/Reference/Global_Objects/Object/constructor ---- -<div>{{JSRef}}</div> - -<p>La proprietà constuctor restituisce un riferimento alla funzione del costruttore {{jsxref ("Object")}} che ha creato l'oggetto istanza. Notare che il valore di questa proprietà è un riferimento alla funzione stessa, non una stringa contenente il nome della funzione.Il valore è di sola lettura solo per i valori primitivi come 1, true e "test".</p> - -<pre dir="ltr" id="tw-target-rmn"></pre> - - - -<h2 id="Description">Description</h2> - -<pre dir="ltr" id="tw-target-text">Tutti gli oggetti (ad eccezione degli object.create (null)) avranno una proprietà constuctor. Gli oggetti creati senza l'uso esplicito di una funzione di constructor (come oggetti letterali e array-letterali) avranno una proprietà constructor che punta al tipo di costrunctor dell'oggetto fondamentale per quell'oggetto.</pre> - -<pre class="brush: js notranslate">let o = {} -o.constructor === Object // true - -let o = new Object -o.constructor === Object // true - -let a = [] -a.constructor === Array // true - -let a = new Array -a.constructor === Array // true - -let n = new Number(3) -n.constructor === Number // true -</pre> - -<h2 id="Examples">Examples</h2> - -<h3 id="Displaying_the_constructor_of_an_object">Displaying the constructor of an object</h3> - -<p>The following example creates a constructor (<code>Tree</code>) and an object of that type (<code>theTree</code>). The example then displays the <code>constructor</code> property for the object <code>theTree</code>.</p> - -<pre class="brush: js notranslate">function Tree(name) { - this.name = name -} - -let theTree = new Tree('Redwood') -console.log('theTree.constructor is ' + theTree.constructor) -</pre> - -<p>This example displays the following output:</p> - -<pre class="brush: js notranslate">theTree.constructor is function Tree(name) { - this.name = name -} -</pre> - -<h3 id="Changing_the_constructor_of_an_object">Changing the constructor of an object</h3> - -<p>One can assign the <code>constructor</code> property for any value except <code>null</code> and <code>undefined</code> since those don't have a corresponding constructor function (like <code>String</code>, <code>Number</code>, <code>Boolean</code> etc.), but values which are primitives won't keep the change (with no exception thrown). This is due to the same mechanism, which allows one to set any property on primitive values (except <code>null</code> and <code>undefined</code>) with no effect. namely wherenever one uses such a primitive as an object an instance of the corresponding constructor is created and discarded right after the statement was executed.</p> - -<pre class="brush: js notranslate">let val = null; -val.constructor = 1; //<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox-stackTrace reps-custom-format">TypeError: <span class="objectBox objectBox-string">var is null</span></span></span></span></span> - -<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox-stackTrace reps-custom-format"><span class="objectBox objectBox-string">val = 'abc';</span></span></span></span></span> -<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox-stackTrace reps-custom-format"><span class="objectBox objectBox-string">val.constructor = Number; //val.constructor === String</span></span></span></span></span> - -<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox-stackTrace reps-custom-format"><span class="objectBox objectBox-string">val.foo = 'bar';</span></span></span></span></span> //An implicit instance of <span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox-stackTrace reps-custom-format"><span class="objectBox objectBox-string">String('abc') was created and assigned the prop foo</span></span></span></span></span> -<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox-stackTrace reps-custom-format"><span class="objectBox objectBox-string">val.foo === undefined; //true, since a new instance of String('abc') was created for this comparison, which doesn't have the foo property</span></span></span></span></span></pre> - -<p>So basically one can change the value of the <code>constructor</code> property for anything, except the primitives mentioned above, <strong>note that changing the </strong><code>constructor</code><strong> property does not affect the instanceof operator</strong>:</p> - -<pre class="brush: js notranslate">let a = []; -a.constructor = String -a.constructor === String // true -a instanceof String //false -a instanceof Array //true - -a = new Foo(); -a.constructor = 'bar' -a.constructor === 'bar' // true - -//etc.</pre> - -<p>If the object is sealed/frozen then the change has no effect and no exception is thrown:</p> - -<pre class="brush: js notranslate">let a = Object.seal({}); -a.constructor = Number; -a.constructor === Object; //true</pre> - -<h3 id="Changing_the_constructor_of_a_function">Changing the constructor of a function</h3> - -<p>Mostly this property is used for defining a function as a <strong>function-constructor</strong> with further calling it with <strong>new</strong> and prototype-inherits chain.</p> - -<pre class="brush: js notranslate">function Parent() { /* ... */ } -Parent.prototype.parentMethod = function parentMethod() {} - -function Child() { - Parent.call(this) // Make sure everything is initialized properly -} -Child.prototype = Object.create(Parent.prototype) // re-define child prototype to Parent prototype - -Child.prototype.constructor = Child // return original constructor to Child</pre> - -<p>But when do we need to perform the last line here? Unfortunately, the answer is: <em>it depends</em>.</p> - -<p>Let's try to define the cases in which re-assignment of the original constructor will play a major role, and when it will be one superfluous line of code.</p> - -<p>Take the following case: the object has the <code>create()</code> method to create itself.</p> - -<pre class="brush: js notranslate">function Parent() { /* ... */ } -function CreatedConstructor() { - Parent.call(this) -} - -CreatedConstructor.prototype = Object.create(Parent.prototype) - -CreatedConstructor.prototype.create = function create() { - return new this.constructor() -} - -new CreatedConstructor().create().create() // TypeError undefined is not a function since constructor === Parent</pre> - -<p>In the example above the exception will be shown since the constructor links to Parent.</p> - -<p>To avoid this, just assign the necessary constructor you are going to use.</p> - -<pre class="brush: js notranslate">function Parent() { /* ... */ } -function CreatedConstructor() { /* ... */ } - -CreatedConstructor.prototype = Object.create(Parent.prototype) -CreatedConstructor.prototype.constructor = CreatedConstructor // sets the correct constructor for future use - -CreatedConstructor.prototype.create = function create() { - return new this.constructor() -} - -new CreatedConstructor().create().create() // it's pretty fine</pre> - -<p>Ok, now it's pretty clear why changing the constructor can be useful.</p> - -<p>Let's consider one more case.</p> - -<pre class="brush: js notranslate">function ParentWithStatic() {} - -ParentWithStatic.startPosition = { x: 0, y:0 } // Static member property -ParentWithStatic.getStartPosition = function getStartPosition() { - return this.startPosition -} - -function Child(x, y) { - this.position = { - x: x, - y: y - } -} - -Child = Object.assign(ParentWithStatic) -Child.prototype = Object.create(ParentWithStatic.prototype) -Child.prototype.constructor = Child - -Child.prototype.getOffsetByInitialPosition = function getOffsetByInitialPosition() { - let position = this.position - let startPosition = this.constructor.getStartPosition() // error undefined is not a function, since the constructor is Child - - return { - offsetX: startPosition.x - position.x, - offsetY: startPosition.y - position.y - } -};</pre> - -<p>For this example we need either to stay parent constructor to continue to work properly or reassign static properties to child's constructor:</p> - -<pre class="brush: js notranslate">... -Child = Object.assign(ParentWithStatic) // Notice that we assign it before we create(...) a prototype below -Child.prototype = Object.create(ParentWithStatic.prototype) -... -</pre> - -<p>or assign parent constructor identifier to a separate property on the Child constructor function and access it via that property:</p> - -<pre class="brush: js notranslate">... -Child.parentConstructor = ParentWithStatic -Child.prototype = Object.create(ParentWithStatic.prototype) -... - let startPosition = this.constructor.parentConstructor.getStartPosition() -... -</pre> - -<div class="blockIndicator note"> -<p><strong>Summary</strong>: Manually updating or setting the constructor can lead to differrent and sometimes confusing consequences. To prevent this, just define the role of <code>constructor</code> in each specific case. In most cases, <code>constructor</code> is not used and reassignment of it is not necessary.</p> -</div> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.Object.constructor")}}</p> - -<h2 id="See_also">See also</h2> - -<div class="hidden"> -<p>The curly braces here invoke standard macroses defined by the MDN wiki. Checkout here for more info: <a href="/en-US/docs/MDN/Contribute/Structures/Macros/Commonly-used_macros">https://developer.mozilla.org/en-US/docs/MDN/Contribute/Structures/Macros/Commonly-used_macros</a></p> -</div> - -<ul> - <li>{{jsxref("statements/class","Class declaration","",1)}}</li> - <li>{{jsxref("Classes/constructor","Class constructor","",1)}}</li> - <li>Glossary: {{Glossary("constructor", "", 1)}}</li> -</ul> 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 deleted file mode 100644 index d2b020b955..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/create/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -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 ---- -<div> - {{JSRef("Global_Objects", "Object")}}</div> -<h2 id="Summary" name="Summary">Sommario</h2> -<p>Il metodo <code><strong>Object.create()</strong></code> crea un nuovo oggetto a partire dall'oggetto prototipo e dalle proprietà specificati.</p> -<h2 id="Syntax" name="Syntax">Sintassi</h2> -<pre class="syntaxbox"><code>Object.create(<var>proto</var>[, <var>propertiesObject</var>])</code></pre> -<h3 id="Parameters" name="Parameters">Parametri</h3> -<dl> - <dt> - <code>proto</code></dt> - <dd> - L'oggetto che farà da prototipo per il nuovo oggetto creato.</dd> - <dt> - <code>propertiesObject</code></dt> - <dd> - 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()")}}.</dd> -</dl> -<h3 id="Throws" name="Throws">Throws</h3> -<p>Lancia un'eccezione di tipo {{jsxref("Global_Objects/TypeError", "TypeError")}} se il parametro <code>proto</code> non è {{jsxref("Global_Objects/null", "null")}} oppure un oggetto.</p> -<h2 id="Examples" name="Examples">Esempi</h2> -<h3 id="Example:_Classical_inheritance_with_Object.create" name="Example:_Classical_inheritance_with_Object.create">Esempio: ereditarietà classica con <code>Object.create</code></h3> -<p>Sotto, trovi un esempio di come implementare un'ereditarietà classica usando <code>Object.create</code>. Si tratta di un'ereditarietà singola, l'unica supportata da Javascript.</p> -<pre class="brush: js">// 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<span style="font-size: 1rem;">? " + (rect instanceof Shape)); // true</span> - -rect.move(1, 1); // Outputs, 'Shape moved.' -</pre> -<p>Se desideri ereditare proprietà e metodi da oggetti multipli, puoi utilizzare dei mixins.</p> -<pre class="brush: js">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 -}; -</pre> -<p>La funzione <code>mixin</code> 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 <a href="http://api.jquery.com/jQuery.extend/">jQuery.extend</a>.</p> -<h3 id="Example:_Using_propertiesObject_argument_with_Object.create" name="Example:_Using_propertiesObject_argument_with_Object.create">Esempio: Usare l'argomento <code>propertiesObject</code> con <code>Object.create</code></h3> -<pre class="brush: js">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 - } -}); -</pre> -<h2 id="Polyfill" name="Polyfill">Polyfill</h2> -<p>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.</p> -<pre class="brush: js">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; - }; - })(); -} -</pre> -<h2 id="Specifications" name="Specifications">Specifiche</h2> -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.8.5.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.create', 'Object.create')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> -<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilità browser</h2> -<div> - {{CompatibilityTable}}</div> -<div id="compat-desktop"> - <table class="compat-table"> - <tbody> - <tr> - <th>Caratteristica</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatChrome("5")}}</td> - <td>{{CompatGeckoDesktop("2")}}</td> - <td>{{CompatIE("9")}}</td> - <td>{{CompatOpera("11.60")}}</td> - <td>{{CompatSafari("5")}}</td> - </tr> - </tbody> - </table> -</div> -<div id="compat-mobile"> - <table class="compat-table"> - <tbody> - <tr> - <th>Caratteristica</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("2")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatOperaMobile("11.50")}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> - </table> -</div> -<p>Basato sulla <a href="http://kangax.github.com/es5-compat-table/">tabella di compatibilità di Kangax</a>.</p> -<h2 id="See_also" name="See_also">Vedi anche</h2> -<ul> - <li>{{jsxref("Object.defineProperty")}}</li> - <li>{{jsxref("Object.defineProperties")}}</li> - <li>{{jsxref("Object.prototype.isPrototypeOf")}}</li> - <li>Il post di John Resig su <a href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf</a></li> -</ul> 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 deleted file mode 100644 index c905420eb2..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/defineproperties/index.html +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Object.defineProperties() -slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties -translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong>Object.defineProperties()</strong> definisce nuove proprietà o modifica le proprietà esistenti, direttamente sull'oggetto di ritorno.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Object.defineProperties(<var>obj</var>, <var>props</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>obj</code></dt> - <dd>L'oggetto su cui definire le nuove proprietà o modificare le esistenti proprietà.</dd> - <dt><code>props</code></dt> - <dd>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:</dd> - <dd> - <dl> - <dt><code>configurable</code></dt> - <dd><code>true</code> se e solo se la proprietà individuata dal descrittore può essere cambiata e se la proprietà può essere cancellata dal presente oggetto.<br> - <strong>Defaults a <code>false</code>.</strong></dd> - <dt><code>enumerable</code></dt> - <dd><code>true</code> se e solo se la proprietà è visualizzabile durante una enumerazione delle proprietà del presente oggetto (es. for-in)<br> - <strong>Defaults a <code>false</code>.</strong></dd> - </dl> - - <dl> - <dt><code>value</code></dt> - <dd>Il valore associato con la proprietà che si sta definendo. Può essere un qualsiasi valore valido di Javascript (number, object, function, ecc...)<br> - <strong>Defaults a {{jsxref("undefined")}}.</strong></dd> - <dt><code>writable</code></dt> - <dd><code>true</code> se e solo se il valore associato per la proprietà può essere cambiato con un {{jsxref("Operators/Assignment_Operators", "operatore di assegnazione", "", 1)}}.<br> - <strong>Defaults to <code>false</code>.</strong></dd> - </dl> - - <dl> - <dt><code>get</code></dt> - <dd>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à<br> - <strong>Defaults a {{jsxref("undefined")}}.</strong></dd> - <dt><code>set</code></dt> - <dd>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à.<br> - <strong>Defaults a {{jsxref("undefined")}}.</strong></dd> - </dl> - </dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'oggetto che è stato passato alla funzione.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>Object.defineProperties</code>, in sostanza, definisce tutte le proprietà di un oggetto, corrispondenti alle proprietà "own" proprie di un oggetto obj.</p> - -<h2 id="Esempio">Esempio</h2> - -<pre class="brush: js">var obj = {}; -Object.defineProperties(obj, { - 'property1': { - value: true, - writable: true - }, - 'property2': { - value: 'Hello', - writable: false - } - // etc. etc. -}); -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>Assumendo di eseguire un ambiente precedente con tutti i nomi e le proprietà che fanno riferimento ai valori iniziali, <code>Object.defineProperties</code> è quasi completamente equivalente (nota il commento in <code>isCallable</code>) al seguente reimplementazione in Javascript:</p> - -<pre class="brush: js;highlight:[8]">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; -} -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.8.5</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Firefox (Gecko)</th> - <th>Chrome</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatGeckoDesktop("2")}}</td> - <td>{{CompatChrome("5")}}</td> - <td>{{CompatIE("9")}}</td> - <td>{{CompatOpera("11.60")}}</td> - <td>{{CompatSafari("5")}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Firefox Mobile (Gecko)</th> - <th>Android</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatGeckoMobile("2")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatOperaMobile("11.5")}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Object.defineProperty()")}}</li> - <li>{{jsxref("Object.keys()")}}</li> - <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> -</ul> 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 deleted file mode 100644 index 26201fdb0c..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/freeze/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Object.freeze() -slug: Web/JavaScript/Reference/Global_Objects/Object/freeze -translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Object.freeze()</strong></code> 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. </p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Object.freeze(<var>obj</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>obj</code></dt> - <dd>L'oggetto da congelare.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'oggetto passato alla funzione.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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)}}).</p> - -<p>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.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">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 -</pre> - -<p>Il seguente esempio mostra come oggetti che sono valori di proprietà possono essere mutati(il congelamento si ferma ad un solo livello di profondità).</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Note">Note</h2> - -<p>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.</p> - -<pre class="brush: js">> Object.freeze(1) -TypeError: 1 is not an object // ES5 code - -> Object.freeze(1) -1 // ES2015 code -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Commento iniziale. Implementato in JavaScript 1.8.5.</td> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-object.freeze', 'Object.freeze')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Firefox (Gecko)</th> - <th>Chrome</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Funzionalità di base</td> - <td>{{CompatGeckoDesktop("2")}}</td> - <td>{{CompatChrome("6")}}</td> - <td>{{CompatIE("9")}}</td> - <td>{{CompatOpera("12")}}</td> - <td>{{CompatSafari("5.1")}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Firefox Mobile (Gecko)</th> - <th>Android</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Funzionalità di base</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li>{{jsxref("Object.isFrozen()")}}</li> - <li>{{jsxref("Object.preventExtensions()")}}</li> - <li>{{jsxref("Object.isExtensible()")}}</li> - <li>{{jsxref("Object.seal()")}}</li> - <li>{{jsxref("Object.isSealed()")}}</li> -</ul> 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 deleted file mode 100644 index dd72c6cdf3..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Object.getPrototypeOf()</strong></code> restituisce il prototipo (ovvero il valore della proprietà interna <code>[[Prototype]]</code>) dell'oggetto specificato.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Object.getPrototypeOf(<var>obj</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>obj</code></dt> - <dd>L'oggetto di cui si vuole ottenere il prototipo.</dd> -</dl> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">var proto = {}; -var obj = Object.create(proto); -Object.getPrototypeOf(obj) === proto; // true -</pre> - -<h2 id="Note">Note</h2> - -<p>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")}}.</p> - -<pre class="brush: js">Object.getPrototypeOf("foo"); -// TypeError: "foo" is not an object (ES5 code) -Object.getPrototypeOf("foo"); -// String.prototype (ES6 code) -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Prima definizione.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_fra_i_Browser">Compatibilità fra i Browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatChrome("5")}}</td> - <td>{{CompatGeckoDesktop("1.9.1")}}</td> - <td>{{CompatIE("9")}}</td> - <td>{{CompatOpera("12.10")}}</td> - <td>{{CompatSafari("5")}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Note_specifiche_su_Opera">Note specifiche su Opera</h2> - -<p>Anche se le vecchie versioni di Opera non supportano ancora il metodo <code>Object.getPrototypeOf()</code>, comunque dalla versione 10.50 è stata implementata la proprietà non standard {{jsxref("Object.proto", "__proto__")}}.</p> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> - <li>{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}</li> - <li>{{jsxref("Object.prototype.__proto__")}}</li> - <li>Il post di John Resig su <a class="external" href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf</a></li> - <li>{{jsxref("Reflect.getPrototypeOf()")}}</li> -</ul> 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 deleted file mode 100644 index 7287ed1e18..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html +++ /dev/null @@ -1,164 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong><code>hasOwnProperty()</code></strong> restituisce un valore booleano che indica se l'oggetto ha la proprietà specificata come propria proprietà (invece di ereditarla).</p> - -<div>{{EmbedInteractiveExample("pages/js/object-prototype-hasownproperty.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>obj</var>.hasOwnProperty(<var>prop</var>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><var>prop</var></dt> - <dd>Il nome della {{jsxref("String")}} o il {{Glossary("Symbol")}} della proprietà da testare.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un {{jsxref("Boolean")}} che indica se l'oggetto ha o meno la proprietà specificata come proprietà propria.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Tutti i discendenti di {{jsxref("Object")}} ereditano il metodo <code>hasOwnProperty</code>. 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.</p> - -<h2 id="Note">Note</h2> - -<p><code>hasOwnProperty</code> restituisce true anche se il valore della proprietà è <code>null</code> o <code>undefined</code>.</p> - -<pre class="brush: js">o = new Object(); -o.propOne = null; -o.hasOwnProperty('propOne'); // ritorna true -o.propTwo = undefined; -o.hasOwnProperty('propTwo'); // ritorna true -</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_hasOwnProperty_per_verificare_l'esistenza_di_una_proprietà">Usare <code>hasOwnProperty</code> per verificare l'esistenza di una proprietà</h3> - -<p>L'esempio seguente determina se l'oggetto o contiene una proprietà denominata <code>prop</code>:</p> - -<pre class="brush: js">o = new Object(); -o.hasOwnProperty('prop'); // ritorna false -o.prop = 'exists'; -o.hasOwnProperty('prop'); // ritorna true -</pre> - -<h3 id="Dirette_vs._proprietà_ereditate">Dirette vs. proprietà ereditate</h3> - -<p>Il seguente esempio distingue tra proprietà dirette e proprietà ereditate attraverso la catena del prototipo:</p> - -<pre class="brush: js">o = new Object(); -o.prop = 'exists'; -o.hasOwnProperty('prop'); // ritorna true -o.hasOwnProperty('toString'); // ritorna false -o.hasOwnProperty('hasOwnProperty'); // ritorna false -</pre> - -<h3 id="Iterare_sulle_proprietà_di_un_oggetto">Iterare sulle proprietà di un oggetto</h3> - -<p>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 <code>hasOwnProperty</code> è strettamente limitato agli elementi enumerabili (come con {{jsxref("Object.getOwnPropertyNames()")}}).</p> - -<pre class="brush: js">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 - } -} -</pre> - -<h3 id="Usare_hasOwnProperty_come_nome_di_una_proprietà">Usare <code>hasOwnProperty</code> come nome di una proprietà</h3> - -<p>JavaScript non protegge il nome della proprietà <code>hasOwnProperty</code>; quindi, se esiste la possibilità che un oggetto possa avere una proprietà con questo nome, è necessario utilizzare un <code>hasOwnProperty</code> <em>esterno</em> per ottenere risultati corretti:</p> - -<pre class="brush: js">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 -</pre> - -<p>Nota che nell'ultimo caso non ci sono oggetti appena creati.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES3')}}</td> - <td>{{Spec2('ES3')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.5.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - - - -<p>{{Compat("javascript.builtins.Object.hasOwnProperty")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerabilità e proprietà delle proprietà</a></li> - <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> - <li>{{jsxref("Statements/for...in", "for...in")}}</li> - <li>{{jsxref("Operators/in", "in")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Guida JavaScript: Ereditarietà rivisitata</a></li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/object/index.html b/files/it/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index 8c567d9ea2..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - JavaScript - - NeedsBrowserCompatibility - - NeedsMobileBrowserCompatibility - - Object - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -<div>{{JSRef("Global_Objects", "Object")}}</div> - -<h2 id="Summary" name="Summary">Sommari</h2> - -<p>Il costruttore <strong>Object</strong> crea un oggetto.</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code><code>// Letterale -{ <em>[ coppiaNomeValore1 [, </em></code></code>coppiaNomeValore<code><code><em>2 [, ...</em></code></code>coppiaNomeValore<code><code><em>N] ] ]</em> } - -// Richiamato come una classe -</code>new Object( <em>[ value ]</em> )</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt>coppiaNomeValore1, coppiaNomeValore2, ... coppiaNomeValoreN</dt> - <dd>Coppie formate da un nome (una stringa) e un valore (di qualsiasi tipo), dove il nome è separato dal valore con i due punti.</dd> - <dd> - <pre class="brush: js">{ - "nome1": "valore1", - nome2: "valore2" // Gli apici nel nome sono opzionali -}; -</pre> - </dd> -</dl> - -<dl> - <dt>value</dt> - <dd>Qualsiasi valore.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>Il costruttore <code>Object</code> 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.</p> - -<p>Quando richiamato come normale funzione, il comportamento di <code>Object()</code> è identico a <code>new Object()</code>.</p> - -<h2 id="Properties" name="Properties">Proprietà del costruttore <code>Object</code></h2> - -<dl> - <dt><code>Object.length</code></dt> - <dd>Ha valore pari a <code>1</code>.</dd> - <dt>{{jsxref("Object.prototype")}}</dt> - <dd>Permette di aggiungere altre proprietà ad ogni oggetto di tipo <code>Object</code>.</dd> -</dl> - -<p>{{ jsOverrides("Function", "Properties", "prototype") }}</p> - -<h2 id="Methods" name="Methods">Metodi del costruttore <code>Object</code></h2> - -<dl> - <dt>{{jsxref("Object.assign()")}} {{experimental_inline}}</dt> - <dd>Crea un nuovo oggetto copiando i valori di tutti le proprietà enumerabili da uno o più oggetti.</dd> - <dt>{{jsxref("Object.create()")}}</dt> - <dd>Crea un nuovo oggetto utilizzando il prototipo e le proprietà specificate.</dd> - <dt>{{jsxref("Object.defineProperty()")}}</dt> - <dd>Aggiunge una proprietà descritta dall'oggetto specificato.</dd> - <dt>{{jsxref("Object.defineProperties()")}}</dt> - <dd>Aggiunge più proprietà descritte dall'oggetto specificato.</dd> - <dt>{{jsxref("Object.freeze()")}}</dt> - <dd>Congela un oggetto: le sue proprietà non possono più essere cancellate o modificate.</dd> - <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> - <dd>Restituisce un oggetto che descriva la proprietà specificata.</dd> - <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> - <dd>Restituisce un array contenente i nomi di tutte le proprietà (enumerabili e non-enumerabili) dell'oggetto specificato.</dd> - <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> - <dd>Restituisce il prototipo dell'oggetto specificato.</dd> - <dt>{{jsxref("Object.is()")}} {{ experimental_inline() }}</dt> - <dd>Determina se due valori sono o no uguali (quindi lo stesso oggetto).</dd> - <dt>{{jsxref("Object.isExtensible()")}}</dt> - <dd>Determina se è permesso estendere un oggetto.</dd> - <dt>{{jsxref("Object.isFrozen()")}}</dt> - <dd>Determina se un oggetto è stato congelato.</dd> - <dt>{{jsxref("Object.isSealed()")}}</dt> - <dd>Determina se un oggetto è stato sigillato.</dd> - <dt>{{jsxref("Object.keys()")}}</dt> - <dd>Restituisce un array contenente i nomi di tutte le proprietà enumerabili dell'oggetto.</dd> - <dt>{{jsxref("Object.observe()")}} {{experimental_inline}}</dt> - <dd>Osserva i cambiamenti di un oggetto in modo asincrono.</dd> - <dt>{{jsxref("Object.preventExtensions()")}}</dt> - <dd>Impedisce ad un oggetto di essere esteso.</dd> - <dt>{{jsxref("Object.seal()")}}</dt> - <dd>Impedisce di eliminare le proprietà di un oggetto.</dd> - <dt>{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}</dt> - <dd> - <p>Imposta i prototipo (quindi la proprietà intena <code>[[Prototype]]</code>) di un oggetto.</p> - </dd> -</dl> - -<p>{{jsOverrides("Function", "Methods", "create", "defineProperty", "defineProperties", "getOwnPropertyDescriptor", "getPrototypeOf")}}</p> - -<h2 id="Object_instances" name="Object_instances">Instanze di <code>Object</code> e l'oggetto prototipo <code>Object</code></h2> - -<p>In JavaScript, tutti gli oggetti sono discendenti di <code>Object</code>; 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à <code>constructor</code> e forniscono un loro metodo <code>toString()</code>. I cambiamenti al prototipo di <code>Object</code> venogno estesi a tutti gli oggetti, eccetto quelli che sovrascrivono le proprietà e i metodi cambiati.</p> - -<h3 id="Properties_of_Object_instances" name="Properties_of_Object_instances">Poprietà</h3> - -<p>{{page('/it/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}</p> - -<h3 id="Methods_of_Object_instances" name="Methods_of_Object_instances">Metodi</h3> - -<p>{{page('/it/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}</p> - -<h2 id="Examples" name="Examples">Esempi</h2> - -<h3 id="Usare_Object_con_i_valori_null_e_undefined">Usare <code>Object</code> con i valori <code>null</code> e <code>undefined</code></h3> - -<p>Questi esempi restituiscono tutti lo stesso oggetto:</p> - -<pre class="brush: js">var o = {};</pre> - -<pre class="brush: js">var o = new Object(); -</pre> - -<pre class="brush: js">var o = new Object(undefined); -</pre> - -<pre class="brush: js">var o = new Object(null); -</pre> - -<h3 id="Usare_Object_per_creare_oggetti_Boolean">Usare <code>Object</code> per creare oggetti <code>Boolean</code></h3> - -<p>I seguenti esempi assegnano alla variabile <code>o</code> un oggetto {{jsxref("Global_Objects/Boolean", "Boolean")}}:</p> - -<pre class="brush: js">var o = new Object(true); -// Equivalente a new Boolean(true)</pre> - -<pre class="brush: js">var o = new Object(Boolean()); -// Equivalente a new Boolean(false)</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 1st Edition. Implemented in JavaScript 1.0</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light',sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<p> </p> 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 deleted file mode 100644 index ffb979fcb5..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/is/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Object.is()</strong></code> determina se i due parametri di input hanno lo <a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness"> stesso valore</a>.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Object.is(<var>value1</var>, <var>value2</var>);</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>value1</code></dt> - <dd>Il primo valore da comparare.</dd> - <dt><code>value2</code></dt> - <dd>Il secondo valore da comparare.</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<p>A {{jsxref("Boolean")}} indicating whether or not the two arguments are the same value.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p><code>Object.is()</code> determina se <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">due valori sono uguali</a>. Due valori sono uguali se sono :</p> - -<ul> - <li>entrambi {{jsxref("undefined")}}</li> - <li>entrambi {{jsxref("null")}}</li> - <li>entrambi <code>true</code> o entrambi <code>false</code></li> - <li>entrambi stringhe della stessa lunghezza con gli stessi caratteri</li> - <li>entrambi lo stesso oggetto</li> - <li>entrambi numeri ed - <ul> - <li>entrambi <code>+0</code></li> - <li>entrambi <code>-0</code></li> - <li>entrambi {{jsxref("NaN")}}</li> - <li>o entrambi non sono 0 ed entrambi non sono {{jsxref("NaN")}} ed entrambi hanno lo stesso valore</li> - </ul> - </li> -</ul> - -<p>Questo <em>non</em> è 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, <code>"" == false</code> risultando <code>true</code>), ma <code>Object.is</code> non converte i loro valori.</p> - -<p>Inoltre questo <em>non</em> è 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 <code>-0</code> e <code>+0</code> come uguali e trattano {{jsxref("Number.NaN")}} differentemente da {{jsxref("NaN")}}.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">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 -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<pre class="brush: js">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; - } - }; -}</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-object.is', 'Object.is')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.is', 'Object.is')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_coi_browser">Compatibilità coi browser</h2> - -<div> -<div class="hidden">La compatibility table su questa pagina è generata da dati strutturali. Se vuoi contribuire per i dati, puoi visitare <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> ed inviarci una pull request.</div> - -<p>{{Compat("javascript.builtins.Object.is")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">Equality comparisons and sameness</a> (in inglese) — un paragone di tutte e tre le facilitazioni per comparare uguaglianze</li> -</ul> 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 deleted file mode 100644 index b1220f1ae5..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/isfrozen/index.html +++ /dev/null @@ -1,184 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Object.isFrozen()</strong></code> determina se un oggetto è {{jsxref("Object.freeze()", "congelato", "", 1)}}.</p> - -<div>{{EmbedInteractiveExample("pages/js/object-isfrozen.html")}}</div> - -<p class="hidden">Il codice sorgente per questo esempio interattivo si trova in una repository di GitHub. Se vuoi contribuire al progetto degli esempi interattivi, puoi clonare <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> ed inviarci una pull request.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><code>Object.isFrozen(<var>obj</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>obj</code></dt> - <dd>L'oggetto da controllare.</dd> -</dl> - -<h3 id="Valori_di_ritorno">Valori di ritorno</h3> - -<p>Un {{jsxref("Boolean")}} che indica se l'oggetto è congelato oppure no.</p> - -<h2 id="Description">Description</h2> - -<p>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.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">// 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 -</pre> - -<h2 id="Note">Note</h2> - -<p>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 <code>true</code>.</p> - -<pre class="brush: js">Object.isFrozen(1); -// TypeError: 1 non è un oggetto (codice in ES5) - -Object.isFrozen(1); -// true (codice in ES2015) -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.12', 'Object.isFrozen')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.8.5.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.isfrozen', 'Object.isFrozen')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.isfrozen', 'Object.isFrozen')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> -<div class="hidden">La compatibility table su questa pagina è generata da dati strutturali. Se vuoi contribuire per i dati, puoi visitare <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> ed inviarci una pull request.</div> - -<p>{{Compat("javascript.builtins.Object.isFrozen")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Object.freeze()")}}</li> - <li>{{jsxref("Object.preventExtensions()")}}</li> - <li>{{jsxref("Object.isExtensible()")}}</li> - <li>{{jsxref("Object.seal()")}}</li> - <li>{{jsxref("Object.isSealed()")}}</li> -</ul> 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 deleted file mode 100644 index d3bdf1b76b..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/issealed/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Object.isSealed()</strong></code> determina se un oggetto è sigillato.</p> - -<div>{{EmbedInteractiveExample("pages/js/object-issealed.html")}}</div> - -<p class="hidden">Il codice sorgente per questo esempio interattivo si trova in una repository di GitHub. Se vuoi contribuire al progetto degli esempi interattivi, puoi clonare <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> ed inviarci una pull request.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><code>Object.isSealed(<var>obj</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>obj</code></dt> - <dd>L'oggetto da controllare.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un {{jsxref("Boolean")}} che indica se l'oggetto è congelato oppure no.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Ritorna <code>true</code> se l'oggetto è sigillato, altrimenti <code>false</code>. 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).</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">// 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à) -</pre> - -<h2 id="Note">Note</h2> - -<p>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 <code>true</code>.</p> - -<pre class="brush: js">Object.isSealed(1); -// TypeError: 1 non è un oggetto (codice in ES5) - -Object.isSealed(1); -// true (codice in ES2015) -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.11', 'Object.isSealed')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.8.5.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.issealed', 'Object.isSealed')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.issealed', 'Object.isSealed')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> -<div class="hidden">Il codice sorgente per questo esempio interattivo si trova in una repository di GitHub. Se vuoi contribuire al progetto degli esempi interattivi, puoi clonare <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> ed inviarci una pull request.</div> - -<p>{{Compat("javascript.builtins.Object.isSealed")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Object.seal()")}}</li> - <li>{{jsxref("Object.preventExtensions()")}}</li> - <li>{{jsxref("Object.isExtensible()")}}</li> - <li>{{jsxref("Object.freeze()")}}</li> - <li>{{jsxref("Object.isFrozen()")}}</li> -</ul> 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 deleted file mode 100644 index ed748c0fad..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/keys/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -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 ---- -<div> - {{JSRef("Global_Objects", "Object")}}</div> -<h2 id="Summary" name="Summary">Sommario</h2> -<p>Il metodo <code><strong>Object.keys()</strong></code> restituisce un array contenente le proprietà enumerabili di un dato oggetto, nel medesimo ordine fornito da un ciclo <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> (la differenza è che un ciclo for-in enumera anche le proprietà nella catena di prototipi).</p> -<h2 id="Syntax" name="Syntax">Sintassi</h2> -<pre class="syntaxbox"><code>Object.keys(<em>obj</em>)</code></pre> -<h3 id="Parameters" name="Parameters">Parametri</h3> -<dl> - <dt> - <em>obj</em></dt> - <dd> - L'oggetto del quale si devono restituire le proprietà enumerabili.</dd> -</dl> -<h2 id="Description" name="Description">Descrizione</h2> -<p><code>Object.keys</code> restituisce un array i quali elementi sono stringhe corrispondenti alle proprietà enumerabili trovate direttamente in <code>obj</code>. L'ordine delle proprietà è lo stesso di quello dato ciclando manualmente sulle proprietà dell'oggetto.</p> -<h2 id="Esempi">Esempi</h2> -<pre class="brush: js">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 -</pre> -<p>Per ottenere tutte le proprietà, anche quelle non enumerabili, si veda {{jsxref("Object.getOwnPropertyNames")}}.</p> -<h2 id="Polyfill">Polyfill</h2> -<p>Per aggiungere un supporto equivalente a <code>Object.keys,</code> in ambienti datati che non lo supportino nativamente, si copi il seguente frammento di codice:</p> -<pre class="brush: js">// 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; - }; - }()); -} -</pre> -<p>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.</p> -<p>Per un semplice polyfill, si veda <a href="http://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html">Javascript - Object.keys Browser Compatibility</a>.</p> -<h2 id="Specifiche">Specifiche</h2> -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale.<br> - implementato in in JavaScript 1.8.5</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.keys', 'Object.keys')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> -<h2 id="Compatibilità_dei_browser">Compatibilità dei browser</h2> -<div> - {{CompatibilityTable}}</div> -<div id="compat-desktop"> - <table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Firefox (Gecko)</th> - <th>Chrome</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto base</td> - <td>4 (2.0)</td> - <td>5</td> - <td>9</td> - <td>12</td> - <td>5</td> - </tr> - </tbody> - </table> -</div> -<div id="compat-mobile"> - <table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Firefox Mobile (Gecko)</th> - <th>Android</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Supporto base</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> - </table> -</div> -<p>Basato su <a href="http://kangax.github.com/es5-compat-table/">Kangax's compat table</a>.</p> -<h2 id="See_also" name="See_also">Vedere anche</h2> -<ul> - <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> - <li>{{jsxref("Object.prototype.propertyIsEnumerable")}}</li> - <li>{{jsxref("Object.create")}}</li> - <li>{{jsxref("Object.getOwnPropertyNames")}}</li> -</ul> 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 deleted file mode 100644 index 4d301b568c..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/seal/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Object.seal()</strong></code> "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.</p> - -<div>{{EmbedInteractiveExample("pages/js/object-prototype-seal.html")}}</div> - -<p class="hidden">Il codice sorgente per questo esempio interattivo si trova in una repository di GitHub. Se vuoi contribuire al progetto degli esempi interattivi, puoi clonare <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> ed inviarci una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>Object.seal(<var>obj</var>)</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>obj</code></dt> - <dd>L'oggetto da sigillare.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'oggetto sigillato.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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)}}).</p> - -<p>Le catene di prototipi non vengono sigillate. Invece, la proprietà {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} viene sigillata.</p> - -<p>Ritorna l'oggetto passato ma sigillato.</p> - -<h2 id="Examples">Examples</h2> - -<pre class="brush: js">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 -</pre> - -<h2 id="Note">Note</h2> - -<p>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.</p> - -<pre class="brush: js">Object.seal(1); -// TypeError: 1 non è un oggetto (codice in ES5) - -Object.seal(1); -// 1 (codice in ES2015) -</pre> - -<h3 id="Differenza_con_Object.freeze">Differenza con <code>Object.freeze()</code></h3> - -<p>Le proprietà esistenti in oggetti congelati con <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze()</a></code> sono rese immutabili. Gli oggetti sigillati con <code>Object.seal()</code> possono ricevere modifiche alle proprietà esistenti.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.3.8', 'Object.seal')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definizione iniziale. Implementato in JavaScript 1.8.5.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.seal', 'Object.seal')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-object.seal', 'Object.seal')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<div> -<div class="hidden">La compatibility table su questa pagina è generata da dati strutturali. Se vuoi contribuire per i dati, puoi visitare <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> ed inviarci una pull request.</div> - -<p>{{Compat("javascript.builtins.Object.seal")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Object.isSealed()")}}</li> - <li>{{jsxref("Object.preventExtensions()")}}</li> - <li>{{jsxref("Object.isExtensible()")}}</li> - <li>{{jsxref("Object.freeze()")}}</li> - <li>{{jsxref("Object.isFrozen()")}}</li> -</ul> 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 deleted file mode 100644 index 5a77ea1a3e..0000000000 --- a/files/it/web/javascript/reference/global_objects/object/tostring/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -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 ---- -<div>{{JSRef("Global_Objects", "Object")}}</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>Il metodo <code><strong>toString()</strong></code> restituisce una stringa a che rappresenta l'oggetto.</p> -<div>{{EmbedInteractiveExample("pages/js/object-prototype-tostring.html")}}</div> - -<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox notranslate"><code><var>obj</var>.toString()</code></pre> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>Ogni oggetto ha un metodo <code>toString()</code> 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 <code>toString()</code> è ereditato da ogni oggetto che discende da <code>Object</code>. Se il metodo non è sovrascritto in un oggetto personalizzato, <code>toString()</code> restituisce "[object <em>type</em>]", dove <code><em>type</em></code> è il tipo di oggetto. Il codice di seguito lo illustra:</p> - -<pre class="brush: js notranslate">var o = new Object(); -o.toString(); // returns [object Object] -</pre> - -<div class="note"> -<p><strong>Nota:</strong> A partire da JavaScript 1.8.5 <code>toString()</code> richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce <code>[object <em>Null</em>]</code>, e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce <code>[object <em>Undefined</em>]</code>, 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")}}.</p> -</div> - -<h2 id="Examples" name="Examples">Esempi</h2> - -<h3 id="Example_Overriding_the_default_toString_method" name="Example:_Overriding_the_default_toString_method">Esempio: Sovrascrittura del metodo di default <code>toString</code> </h3> - -<p>Puoi creare una funzione che deve essere richiamata al posto del default metodo <code>toString()</code>. Il metodo <code>toString()</code> non prende argomenti e deve restituire una stringa. Esso può assumere qualunque valore tu voglia, ma sarà molto utile se comunichi informazioni sull'oggetto.</p> - -<p>Il codice seguente definisce l'oggetto <code>Dog</code> e crea <code>theDog</code>, ovvero un oggetto di tipo <code>Dog</code>:</p> - -<pre class="brush: js notranslate">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'); -</pre> - -<p>Richiamando il metodo <code>toString()</code> su questo oggetto personalizzato, esso restituisce il valore di default ereditato da {{jsxref("Global_Objects/Object", "Object")}}:</p> - -<pre class="brush: js notranslate">theDog.toString(); // returns [object Object] -</pre> - -<p>Il codice seguente crea e assegna il metodo <code>dogToString()</code> per sovrascrivere il metodo di default <code>toString()</code>. Questa funzione genera una stringa contenente i valori name, breed, color e sex dell'oggetto, nella forma di "<code>property = value;</code>".</p> - -<pre class="brush: js notranslate">Dog.prototype.toString = function dogToString() { - var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; - return ret; -} -</pre> - -<p>Col precedente codice, la funzione <code>dogToString()</code> è richiamata automaticamente da JavaScript ogni volta che l'oggetto <code style="font-style: normal;">theDog</code> è usato in un contesto string, e restituisce la seguente stringa:</p> - -<pre class="notranslate">Dog Gabby is a female chocolate Lab -</pre> - -<h3 id="Example_Using_toString_to_detect_object_type" name="Example:_Using_toString_to_detect_object_type">Esempio: Uso di <code>toString()</code> per individuare l'oggetto class</h3> - -<p><code>toString()</code> può essere usato con ogni oggetto e permette di ottenere il suo class. Per usare <code>Object.prototype.toString()</code> 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 <code>thisArg</code>.</p> - -<pre class="brush: js notranslate">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] -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>ECMAScript 1 Edizione.</td> - <td>Standard</td> - <td>Definizione iniziale. Implementato in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce <code>[object <em>Null</em>]</code>, e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce <code>[object <em>Undefined</em>]</code></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Caratteristiche</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Support Base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Support Base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also" name="See_also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Object.prototype.toSource()")}}</li> - <li>{{jsxref("Object.prototype.valueOf()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/parsefloat/index.html b/files/it/web/javascript/reference/global_objects/parsefloat/index.html deleted file mode 100644 index f587064676..0000000000 --- a/files/it/web/javascript/reference/global_objects/parsefloat/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: parseFloat() -slug: Web/JavaScript/Reference/Global_Objects/parseFloat -translation_of: Web/JavaScript/Reference/Global_Objects/parseFloat ---- -<div> - <div> - <div> - {{jsSidebar("Objects")}}</div> - </div> -</div> -<h2 id="Sommario">Sommario</h2> -<p>La funzione <code><strong>parseFloat()</strong></code> riceve una stringa come argomento e ritorna un numero in virgola mobile.</p> -<h2 id="Sintassi">Sintassi</h2> -<pre class="syntaxbox">parseFloat(<em>string</em>)</pre> -<h3 id="Parametri">Parametri</h3> -<dl> - <dt> - <code>string</code></dt> - <dd> - Una stringa che rapprestena il valore da analizzare.</dd> -</dl> -<h2 id="Descrizione">Descrizione</h2> -<p><code>parseFloat</code> è una funzione primo livello ( globale ) e non è associata con nessun oggetto.</p> -<p><code>parseFloat</code> 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.</p> -<p>Se il primo carattere dell'argomento non può essere analizzato, <code>parseFloat</code> ritorna <code>NaN</code>.</p> -<p>Per questioni aritmetiche, il valore <span style="font-family: Consolas, Monaco, 'Andale Mono', monospace; line-height: 1.5;">NaN </span><span style="line-height: 1.5;">non è di tipo numerico. Per determinare se il risultato di ParseFloat è </span><code>NaN</code><span style="line-height: 1.5;"> occorre chiamare la funzione </span><span style="line-height: 1.5;">{{jsxref("Global_Objects/isNaN", "isNaN")}}. Se <code>NaN</code> viene utilizzato per un operazione aritmetica, la stessa risulterà <code>NaN</code></span>.</p> -<p><font face="Consolas, Monaco, Andale Mono, monospace">parseFloat </font>può analizzare e ritornare il valore<font face="Consolas, Monaco, Andale Mono, monospace"> Infinity. </font>La funzione<font face="Consolas, Monaco, Andale Mono, monospace"><code> </code></font><span style="line-height: 1.5;">{{jsxref("Global_Objects/isNaN", "isNaN")}} consente di determinare se il risultato è un numero finito </span><span style="line-height: 1.5;"> (not </span><code style="font-style: normal; line-height: 1.5;">Infinity</code><span style="line-height: 1.5;">, </span><code style="font-style: normal; line-height: 1.5;">-Infinity</code><span style="line-height: 1.5;">, o </span><code style="font-style: normal; line-height: 1.5;">NaN</code><span style="line-height: 1.5;">).</span></p> -<h2 id="Esempi">Esempi</h2> -<h3 id="Esempio_parseFloat_ritorna_un_numero">Esempio: <code>parseFloat</code> ritorna un numero</h3> -<p>Tutti gli esempi seguenti ritornano 3.14</p> -<pre class="brush:js">parseFloat("3.14"); -parseFloat("314e-2"); -parseFloat("0.0314E+2"); -parseFloat("3.14altri caratteri non numerici"); -</pre> -<h3 id="Esempio_parseFloat_ritorna_NaN">Esempio: <code>parseFloat</code> ritorna NaN</h3> -<p>L'esempio seguente ritorna il valore <code>NaN</code></p> -<pre class="brush: js">parseFloat("FF2"); -</pre> -<h3 id="Una_funzione_di_analisi_più_approfondita.">Una funzione di analisi più approfondita.</h3> -<p>Talvolta può essere necessario un maggior controllo sulla funzione di parse, le regular expression possono aiutare :</p> -<pre class="brush: js">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 -</pre> -<p>Nota: questo codice è a scopo esplicativo. La funzione non accetta numeri validi come 1. o .5+</p> -<h2 id="Specifiche">Specifiche</h2> -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>ECMAScript 1a Edizione.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.2.3', 'parseFloat')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-parsefloat-string', 'parseFloat')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> -<h2 id="Compatibilità_Browser">Compatibilità Browser</h2> -<p>{{ CompatibilityTable() }}</p> -<div id="compat-desktop"> - <table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> - </table> -</div> -<div id="compat-mobile"> - <table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> - </table> -</div> -<h2 id="See_Also" name="See_Also">Leggi anche:</h2> -<ul> - <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> - <li>{{jsxref("Number.parseFloat()")}}</li> - <li>{{jsxref("Number.parseInt()")}}</li> - <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/parseint/index.html b/files/it/web/javascript/reference/global_objects/parseint/index.html deleted file mode 100644 index c6300b4b3e..0000000000 --- a/files/it/web/javascript/reference/global_objects/parseint/index.html +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: parseInt() -slug: Web/JavaScript/Reference/Global_Objects/parseInt -translation_of: Web/JavaScript/Reference/Global_Objects/parseInt ---- -<div>{{jsSidebar("Objects")}}</div> - -<p>La funzione <code><strong>parseInt()</strong></code> analizza un argomento stringa e restituisce un numero intero della radice specificata (la base nei sistemi numerici matematici).</p> - -<div>{{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}}</div> - - - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">parseInt(<em>string</em>, <em>radix</em>);</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>string</code></dt> - <dd>Il valore da analizzare. Se l'argomento <code>string</code> non è una stringa, viene convertito in una stringa (utilizzando l'operazione astratta <code><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-tostring">ToString</a></code>). Gli spazi bianchi iniziali nell'argomento stringa vengono ignorati.</dd> - <dt><code>radix</code></dt> - <dd>Un numero intero compreso tra 2 e 36 che rappresenta la <em>radice</em> (la base nei sistemi numerici matematici) della stringa sopra menzionata.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Un numero intero analizzato dalla stringa specificata. Se il primo carattere non può essere convertito in un numero, viene restituito {{jsxref("NaN")}}.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>La funzione <code>parseInt</code> converte il suo primo argomento in una stringa, lo analizza e restituisce un numero intero o <code>NaN</code>. Se non è <code>NaN</code>, il valore restituito sarà l'intero che è il primo argomento preso come numero nella <em>radice</em> specificata (base). Ad esempio, una <em>radice</em> di 10 indica la conversione da un numero decimale, 8 ottali, 16 esadecimali e così via. Per le radici sopra <code>10</code>, le lettere dell'alfabeto indicano numeri maggiori di <code>9</code>. Ad esempio, per i numeri esadecimali (base 16), vengono utilizzate le lettere da <code>A</code> a <code>F</code>.</p> - -<p>Se <code>parseInt</code> 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. <code>parseInt</code> tronca i numeri ai valori interi. Sono ammessi spazi iniziali e finali.</p> - -<p>Poiché alcuni numeri includono il carattere <code>e</code> nella loro rappresentazione di stringa (ad esempio <strong><code>6.022e23</code></strong>), l'uso di <code>parseInt</code> per troncare valori numerici produrrà risultati imprevisti se utilizzato su numeri molto grandi o molto piccoli. <code>parseInt</code> non dovrebbe essere usato come sostituto di {{jsxref("Math.floor()")}}.</p> - -<p>Se <em>radix</em> è <code>undefined</code> o 0 (o assente), JavaScript assume quanto segue:</p> - -<ul> - <li>Se l'input <code>string</code> inizia con "0x" o "0X", radix è 16 (esadecimale) e il resto della stringa viene analizzato.</li> - <li>Se l'input <code>string</code> inizia con "0", radix è otto (ottale) o 10 (decimale). Esattamente quale radix è scelto dipende dall'implementazione. ECMAScript 5 specifica che viene utilizzato 10 (decimale), ma non tutti i browser lo supportano ancora. Per questo motivo <strong>specifica sempre una radice quando usi <code>parseInt</code></strong>.</li> - <li>Se l'input <code>string</code> inizia con qualsiasi altro valore, la radice è 10 (decimale).</li> -</ul> - -<p>Se il primo carattere non può essere convertito in un numero, <code>parseInt</code> restituisce <code>NaN</code>.</p> - -<p>Per scopi aritmetici, il valore <code>NaN</code> vnon è un numero in nessuna radice. È possibile chiamare la funzione {{jsxref("isNaN")}} per determinare se il risultato di <code>parseInt</code> è <code>NaN</code>. Se <code>NaN</code> viene passato alle operazioni aritmetiche, i risultati dell'operazione saranno anche <code>NaN</code>.</p> - -<p>Per convertire il numero nella sua stringa letterale in una particolare radix, usa <code>intValue.toString(radix)</code>.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_parseInt">Usare parseInt</h3> - -<p>Tutti gli esempi seguenti restituiscono <strong><code>15</code></strong>:</p> - -<pre class="brush: js">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); -</pre> - -<p>I seguenti esempi restituiscono tutti <strong><code>NaN</code></strong>:</p> - -<pre class="brush: js">parseInt('Hello', 8); // Non è un numero -parseInt('546', 2); // Le cifre non sono valide per le rappresentazioni binarie -</pre> - -<p>Tutti gli esempi seguenti restituiscono <strong><code>-15</code></strong>:</p> - -<pre class="brush: js">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); -</pre> - -<p>Tutti gli esempi seguenti restituiscono <code><strong>4</strong></code>:</p> - -<pre class="brush: js">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 -</pre> - -<p>L'esempio seguente restituisce <code><strong>224</strong></code>:</p> - -<pre class="brush: js">parseInt('0e0', 16); -</pre> - -<h2 id="Interpretazioni_ottali_senza_radix">Interpretazioni ottali senza radix</h2> - -<p>Sebbene scoraggiato da ECMAScript 3 e proibito da ECMAScript 5, molte implementazioni interpretano una stringa numerica che inizia con uno <code>0</code> iniziale come ottale. Il seguente potrebbe avere un risultato ottale o potrebbe avere un risultato decimale. <strong>Specifica sempre una radice per evitare questo comportamento inaffidabile.</strong></p> - -<pre class="brush: js">parseInt('0e0'); // 0 -parseInt('08'); // 0, '8' non è una cifra ottale. -</pre> - -<h3 id="ECMAScript_5_rimuove_l'interpretazione_ottale">ECMAScript 5 rimuove l'interpretazione ottale</h3> - -<p>La specifica ECMAScript 5 della funzione <code>parseInt</code> non consente più alle implementazioni di trattare le stringhe che iniziano con un carattere <code>0</code> come valori ottali. ECMAScript 5 afferma:</p> - -<p>La funzione <code>parseInt</code> 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 <code>0</code>, si presume che sia <code>10</code> tranne quando il numero inizia con le coppie di caratteri <code>0x</code> o <code>0X</code>, nel qual caso si assume una radice di 16.</p> - -<p>Ciò differisce da ECMAScript 3, che scoraggiava, ma consentiva l'interpretazione ottale.</p> - -<p>Molte implementazioni non hanno adottato questo comportamento a partire dal 2013 e, poiché i browser più vecchi devono essere supportati, <strong>specificare sempre una radice.</strong></p> - -<h2 id="Una_funzione_di_analisi_più_rigorosa">Una funzione di analisi più rigorosa</h2> - -<p>A volte è utile avere un modo più rigoroso di analizzare i valori int. Le espressioni regolari possono aiutare:</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.2.2', 'parseInt')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-parseint-string-radix', 'parseInt')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-parseint-string-radix', 'parseInt')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - - - -<p>{{Compat("javascript.builtins.parseInt")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> - <li>{{jsxref("Number.parseFloat()")}}</li> - <li>{{jsxref("Number.parseInt()")}}</li> - <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> - <li>{{jsxref("Number.toString()")}}</li> - <li>{{jsxref("Object.valueOf")}}</li> -</ul> 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 deleted file mode 100644 index 4d1c9a970c..0000000000 --- a/files/it/web/javascript/reference/global_objects/promise/all/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Promise.all() -slug: Web/JavaScript/Reference/Global_Objects/Promise/all -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Promise.all(iterable)</strong></code> 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.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>Promise.all(iterable)</var>;</pre> - -<h3 id="Parameteri">Parameteri</h3> - -<dl> - <dt>iterable</dt> - <dd>Un oggetto iterabile, come un {{jsxref("Array")}}. See <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a>.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>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</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <strong>Promise.all </strong>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")}}. </p> - -<p>Se uno qualsiasi dei promise passati viene rigettato, il metodo <code>all</code> 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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_Promise.all">Usare <code>Promise.all</code></h3> - -<p><code>Il metodo Promise.all</code> aspetta la risoluzione di tutti i promise (od il primo che viene rigettato).</p> - -<pre class="brush: js">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"] -});</pre> - -<h3 id="Promise.all_comportamento_fail-fast"><code>Promise.all</code> comportamento fail-fast</h3> - -<p>Il metodo <code>Promise.all</code> viene rigettato se uno degli elementi viene rigettato e <code>Promise.all</code> viene rigettato immediatamente. In caso quattro promise vengono risolti dopo un timeout, e uno viene rigettato immediatamente: allora <code>Promise.all</code> viene rigettato immediamente.</p> - -<pre class="brush: js">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" -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Status</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-promise.all', 'Promise.all')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Definizione iniziale nello standard ECMA.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilitá_dei_browser">Compatibilitá dei browser</h2> - -<p class="hidden">To contribute to this compatibility data, please write a pull request against this file: <a href="https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json">https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json</a>.</p> - -<p>{{Compat}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Promise")}}</li> - <li>{{jsxref("Promise.race()")}}</li> -</ul> 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 deleted file mode 100644 index 0b9b906153..0000000000 --- a/files/it/web/javascript/reference/global_objects/promise/catch/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Promise.prototype.catch() -slug: Web/JavaScript/Reference/Global_Objects/Promise/catch -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong>catch()</strong> restituisce una <code>Promise</code> e si occusa esclusivamente nei casi respinti. Si comporta come una chiamata {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.</p> - -<p> </p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>p.catch(onRejected)</var>; - -p.catch(function(reason) { - // rejection -}); -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt>onRejected</dt> - <dd>Una {{jsxref("Function")}} chiamata quando la <code>Promise</code> viene respinta. Questa funzione richiede un parametro, la motivazione della respinta.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code>catch</code> può essere utile per gestire errori nella composizione delle promise.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Uso_del_metodo_catch">Uso del metodo catch</h3> - -<pre class="brush: js">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!" -}); -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition in an ECMA standard.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>32</td> - <td>{{CompatGeckoDesktop(29.0)}} [1]</td> - <td>{{CompatNo}}</td> - <td>19</td> - <td>7.1</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - <th>Chrome for Android</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatGeckoMobile(29.0)}} [1]</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - <td>32</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Gecko 24 has an experimental implementation of <code>Promise</code>, under the initial name of <code>Future</code>. It got renamed to its final name in Gecko 25, but disabled by default behind the flag <code>dom.promise.enabled</code>. <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=918806">Bug 918806</a> enabled Promises by default in Gecko 29.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Promise")}}</li> - <li>{{jsxref("Promise.prototype.then()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/promise/index.html b/files/it/web/javascript/reference/global_objects/promise/index.html deleted file mode 100644 index d2f579bc51..0000000000 --- a/files/it/web/javascript/reference/global_objects/promise/index.html +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Promise -slug: Web/JavaScript/Reference/Global_Objects/Promise -tags: - - ECMAScript 2015 - - JavaScript - - Promise - - async -translation_of: Web/JavaScript/Reference/Global_Objects/Promise ---- -<div>{{JSRef}}</div> - -<p>Gli oggetti <strong><code>Promise</code></strong> sono usati per computazioni in differita e asincrone. Una <code>Promise</code> rappresenta un'operazione che non è ancora completata, ma lo sarà in futuro.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="brush: js">new Promise(function(resolve, reject) { ... });</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt>executor</dt> - <dd> - <p>Una funzione che ha due argomenti: <code>resolve</code> e <code>reject</code>. Tale funzione viene chiamata immediatamente dall'implementazione della Promise, passando i due argomenti <code>resolve</code> e <code>reject,</code> che sono due funzioni. Le due funzioni <code>resolve</code> e <code>reject</code>, quando chiamate, risolvono o rigettano la promise. L'esecutore inizia del lavoro (solitamente asincrono), e, una volta completato, chiama <code>resolve</code> per risolvere la promise, o <code>reject</code> se c'è stato qualche errore. Se un errore viene sollevato nella funzione di esecuzione <code>(executor)</code> la promise viene rigettata.</p> - </dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Una <code><strong>Promise</strong></code> 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 <em>promise</em>, tramite la quale si potrà ottenere il valore di completamento una volta che la promise sarà terminata.</p> - -<p>Una <code>Promise</code> può presentarsi in uno dei seguenti stati:</p> - -<ul> - <li><em>pending </em>(attesa): stato iniziale, né soddisfatto né respinto.</li> - <li><em>fulfilled </em>(soddisfatto): significa che l'operazione si è conclusa con sucesso.</li> - <li><em>rejected</em> (respinto): significa che l'operazione à fallita.</li> -</ul> - -<p>Una promise in <em>pending</em> può evolvere sia in <em>fulfilled </em>con un valore, sia in <em>rejected</em> con una motivazione (errore). Quando accade una di queste situazioni, vengono chiamati gli handler associati che sono stati accodati dal metodo <code>then</code> 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).</p> - -<p><font face="Open Sans, Arial, sans-serif">Poichè i metodi </font><code>{{jsxref("Promise.then", "Promise.prototype.then")}}</code> e <code>{{jsxref("Promise.catch", "Promise.prototype.catch")}}</code> restituiscono delle promise, è possibile concatenarli tramite l'operazione di <em>composition</em>.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png"></p> - -<div class="note"> -<p><strong>Da non confondere con: </strong>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 <a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions_and_function_scope/Arrow_functions">arrow function</a> senza argomenti: <code>f = () => <em>expression</em></code> per creare un'espressione non valutata immediatamente (lazy-evaluated) ed usare <code>f()</code> per valutarla.</p> -</div> - -<div class="note"> -<p><strong>Nota</strong>: Si dice che una promise è "ferma" (<em>settled) </em>se è soddisfatta o respinta, ma non in <em>pending</em>. Si può parlare anche di promessa "risolta" (<em>resolved</em>) quando la promise è ferma o è bloccata in una catena di promise. <a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a> di Domenic Denicola contiene maggiori dettagli sulla terminologia riguardo le promise.</p> -</div> - -<h2 id="Proprietà">Proprietà</h2> - -<dl> - <dt><code>Promise.length</code></dt> - <dd>La proprietà length (lunghezza) ha come valore 1 (numero di argomenti del costruttore).</dd> - <dt>{{jsxref("Promise.prototype")}}</dt> - <dd>Rappresenta il prototype per il costruttore della <code>Promise</code>.</dd> -</dl> - -<h2 id="Metodi">Metodi</h2> - -<dl> - <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt> - <dd>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 <code>Iterable</code> 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.</dd> - <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt> - <dd>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.</dd> -</dl> - -<dl> - <dt>{{jsxref("Promise.reject", "Promise.reject(reason)")}}</dt> - <dd>Restituisce un oggetto <code>Promise</code> che è respinta con la data motivazione.</dd> -</dl> - -<dl> - <dt>{{jsxref("Promise.resolve", "Promise.resolve(value)")}}</dt> - <dd>Restituise un oggetto <code>Promise</code> che è risolto con il valore dato. Se il valore é un thenable (es. ha un metodo <code>then</code>), 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.</dd> -</dl> - -<h2 id="Promise_prototype">Promise prototype</h2> - -<h3 id="Proprietà_2">Proprietà</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}</p> - -<h3 id="Metodi_2">Metodi</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}</p> - -<h2 id="Creazione_di_una_Promise">Creazione di una Promise</h2> - -<p>Un oggetto di tipo <code>Promise</code>, viene creato con la keyowrd <code>new</code> ed il suo costruttore. Questo costruttore accetta come argomento una funzione, chiamata "<code>funzione esecutore (executor function)</code>". Questa funzione accetta altre due funzioni come parametri. La prima (<code>resolve</code>) viene eseguita in modo asincrono quando l'operazione viene eseguita con successo e restituisce il risultato dell'operazione come valore. La seconda (<code>reject</code>) 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 <code>Error</code></p> - -<pre class="brush: js" dir="rtl">const myFirstPromise = new Promise((resolve, reject) => { - // esegue qualcosa di asincrono che eventualmente chiama: - // - resolve(someValue); // fulfilled - // oppure - reject("motivo del fallimento"); // rejected -});</pre> - -<p>Per creare una funzione con il comportamento di Promise, semplicemente restituisci una promise</p> - -<pre class="brush: js">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(); - }); -}</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Esempio_semplice">Esempio semplice</h3> - -<pre class="brush: js">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); -});</pre> - -<h3 id="Esempio_avanzato">Esempio avanzato</h3> - -<pre class="brush: html"><button id="btn">Make a promise!</button> -<div id="log"></div></pre> - -<p>Questo piccolo esempio mostra il meccanismo delle <code>Promise</code>. Il metodo <code>testPromise()</code> 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 <code>Promise</code> viene utilizzato per creare la promise.</p> - -<p>La risoluzione della promise viene semplicemente loggata tramite una funzione di callback <code>fulfill</code> {{jsxref("Promise.prototype.then()","p1.then()")}}. Una serie di log mostrano che il comportamento sincrono del metodo è disaccoppiato rispetto all'esecuzione asincrona della promise.</p> - -<pre class="brush: js">'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."; -}</pre> - -<p>In questo esempio si comincia cliccando il bottone. Per testare necessiti di un browser che supporta le <code>Promise</code>. Cliccando il bottone diverse volte in un lasso di tempo breve vedrai che le funzioni verranno risolte una dopo l'altra.</p> - -<h2 id="Caricare_un'immagine_con_XHR">Caricare un'immagine con XHR</h2> - -<p>Un'altro semplice esempio che utilizza le Promise e <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> mostra come caricare un'immagine è disponibile sul <a href="https://github.com/mdn/js-examples/tree/master/promises-test">repository</a> 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.</p> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td> - <p>Prima definizione in uno standard ECMA.</p> - </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> - <p> </p> - </td> - </tr> - </tbody> -</table> - -<h2 id="Supporto_dei_browser">Supporto dei browser</h2> - -<p>{{Compat("javascript.builtins.Promise")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Using promises</a></li> - <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li> - <li><a href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li> - <li><a href="https://medium.com/@ramsunvtech/js-promise-part-2-q-js-when-js-and-rsvp-js-af596232525c#.dzlqh6ski">Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)</a></li> - <li><a href="https://tech.io/playgrounds/11107/tools-for-promises-unittesting/introduction">Venkatraman.R - Tools for Promises Unit Testing</a></li> - <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Jake Archibald: JavaScript Promises: There and Back Again</a></li> - <li><a href="http://de.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript">Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript</a></li> - <li><a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">Matt Greer: JavaScript Promises ... In Wicked Detail</a></li> - <li><a href="https://www.promisejs.org/">Forbes Lindesay: promisejs.org</a></li> - <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li> - <li><a href="https://www.udacity.com/course/javascript-promises--ud898">Udacity: JavaScript Promises</a></li> - <li> </li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/proxy/index.html b/files/it/web/javascript/reference/global_objects/proxy/index.html deleted file mode 100644 index fa35ff1d43..0000000000 --- a/files/it/web/javascript/reference/global_objects/proxy/index.html +++ /dev/null @@ -1,396 +0,0 @@ ---- -title: Proxy -slug: Web/JavaScript/Reference/Global_Objects/Proxy -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy ---- -<div> -<div>{{JSRef}}</div> - -<div>L'oggetto <strong>Proxy</strong> è utilizzato per definire comportamenti personalizzati per operazioni fondamentali (per esempio: ricerca delle proprietà, assegnazione, enumerazione, invocazione delle funzioni, ecc.).</div> -</div> - -<h2 id="Terminologia">Terminologia</h2> - -<dl> - <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">handler</a></dt> - <dd>Oggetto placeholder, il quale contiene le trappole.</dd> - <dt>traps</dt> - <dd>I metodi che forniscono l'accesso alle proprietà. Questo è analogo al concetto di trappola nei sistemi operativi.</dd> - <dt>target</dt> - <dd>Oggetti, che i proxy virtualizzano (sostituiscono). <span class="short_text" id="result_box" lang="it"><span>Viene spesso utilizzato come back-end di archiviazione per il proxy</span></span>. Le invarianti, riguardanti oggetti non estensibili o proprietà non configurabili, sono verificate prima di interagire con l'obiettivo.</dd> -</dl> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">var p = new Proxy(target, handler); -</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>target</code></dt> - <dd>Un oggetto target che il Proxy ingloberà. Può essere un qualsiasi tipo di oggetto, array nativi inclusi, funzioni o anche altri Proxy.</dd> - <dt><code>handler</code></dt> - <dd>Un oggetto le cui proprietà sono funzioni che definiscono i comportamenti del proxy quando un'operazione viene effettuata su di esso.</dd> -</dl> - -<h2 id="Metodi">Metodi</h2> - -<dl> - <dt>{{jsxref("Proxy.revocable()")}}</dt> - <dd>Crea un oggetto Proxy revocabile.</dd> -</dl> - -<h2 id="Metodi_dell'handler_object">Metodi dell'handler object</h2> - -<p>L'oggetto handler è un oggetto placeholder, il quale contiene le trappole per il Proxy.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Esempio_base">Esempio base</h3> - -<p>In questo esempio base il numero <code>37</code> viene restituito come valore di default quando l'oggetto non contiene la proprietà richiesta. Viene utilizzato il <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/get">get</a></code> handler.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="No-op_forwarding_proxy">No-op forwarding proxy</h3> - -<p>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. </p> - -<pre class="brush: js">var target = {}; -var p = new Proxy(target, {}); - -p.a = 37; // operazione inoltrata al target - -console.log(target.a); // 37. Operazione inoltrata con successo -</pre> - -<h3 id="Validation">Validation</h3> - -<p>Con un proxy, puoi facilmente validare il valore passato per un oggetto. In questo esempio viene utilizzato il <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/get">set </a></code>handler.</p> - -<pre class="brush: js">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</pre> - -<h3 id="Extending_constructor">Extending constructor</h3> - -<p>Una funzione proxy può facilmente estendere un costruttore con un nuovo costruttore. Questo esempio usa gli handler: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/construct"><code>construct</code></a> e <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply"><code>apply</code></a> .</p> - -<pre class="brush: js">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</pre> - -<h3 id="Manipulating_DOM_nodes">Manipulating DOM nodes</h3> - -<p>Alcune volte vorresti attivare o disattivare un attributo o una classe di due elementi differenti. Qui è mostrato come è possibile farlo utilizzando il <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set"><code>set</code></a> handler.</p> - -<pre class="brush: js">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'</pre> - -<h3 id="Value_correction_and_an_extra_property">Value correction and an extra property</h3> - -<p>L'oggetto <code>products</code> del proxy valuta il valore passato e lo converte in un array se è necessario. L'oggetto supporta anche una proprietà extra chiamata <code>latestBrowser</code>, uttilizzabile sia come getter che come setter.</p> - -<pre class="brush: js">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'</pre> - -<h3 id="Trovare_un_oggetto_in_un_array_dalla_sua_proprietà">Trovare un oggetto in un array dalla sua proprietà</h3> - -<p>Questo proxy estende un array con alcune caratteristiche utiliti. Come puoi notare, puoi facilmente definire nuove proprietà senza utilizzare <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties"><code>Object.defineProperties</code></a>. Questo esempio può essere adattato per trovare una riga di una tabella partendo dalla sua cella. In questo caso il target sarà <a href="https://developer.mozilla.org/en-US/docs/DOM/table.rows"><code>table.rows</code></a>.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="Una_lista_completa_di_traps">Una lista completa di traps</h3> - -<p>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 <code>docCookies</code> creato da <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework" title="https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support">the "little framework" published on the <code>document.cookie</code> page</a>.</p> - -<pre class="brush: js">/* - 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);</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-proxy-objects', 'Proxy')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES2016', '#sec-proxy-objects', 'Proxy')}}</td> - <td>{{Spec2('ES2016')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES2017', '#sec-proxy-objects', 'Proxy')}}</td> - <td>{{Spec2('ES2017')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-proxy-objects', 'Proxy')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_tra_Browser">Compatibilità tra Browser</h2> - - - -<p>{{Compat("javascript.builtins.Proxy", 2)}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a class="external" href="https://www.youtube.com/watch?v=sClk6aB_CPk">"Proxies are awesome" Brendan Eich presentation at JSConf</a> (<a class="external" href="http://www.slideshare.net/BrendanEich/metaprog-5303821">slides</a>)</li> - <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">ECMAScript Harmony Proxy proposal page</a> and <a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies_semantics">ECMAScript Harmony proxy semantics page</a></li> - <li><a class="external" href="http://soft.vub.ac.be/~tvcutsem/proxies/">Tutorial on proxies</a></li> - <li><a href="/en-US/docs/JavaScript/Old_Proxy_API" title="/en-US/docs/JavaScript/Old_Proxy_API">SpiderMonkey specific Old Proxy API</a></li> - <li>{{jsxref("Object.watch()")}} is a non-standard feature but has been supported in Gecko for a long time.</li> -</ul> - -<h2 id="Nota_di_licenza"><span class="short_text" id="result_box" lang="it"><span>Nota di licenza</span></span></h2> - -<p>Alcuni contentui (test, esempi) in questa pagina sono stati copiati o adattatu dall' <a class="external" href="http://wiki.ecmascript.org/doku.php">ECMAScript wiki</a> i quali contenuti sono sotto licenza <a class="external" href="http://creativecommons.org/licenses/by-nc-sa/2.0/">CC 2.0 BY-NC-SA</a>.</p> diff --git a/files/it/web/javascript/reference/global_objects/proxy/proxy/apply/index.html b/files/it/web/javascript/reference/global_objects/proxy/proxy/apply/index.html deleted file mode 100644 index 16c5a8dcb2..0000000000 --- a/files/it/web/javascript/reference/global_objects/proxy/proxy/apply/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: handler.apply() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply -tags: - - ECMAScript 2015 - - JavaScript - - Proxy - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply -original_slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong><code>handler.apply()</code></strong> costituisce una trap per una chiamata a funzione.</p> - -<div>{{EmbedInteractiveExample("pages/js/proxyhandler-apply.html", "taller")}}</div> - -<p class="hidden">Il sorgente di questo esempio interattivo è memorizzato in una repository GitHub. Qualora volessi contribuire al progetto degli esempi interattivi, puoi farlo clonando <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviandoci una pull request.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="brush: js">var p = new Proxy(target, { - apply: function(target, thisArg, argumentsList) { - } -}); -</pre> - -<h3 id="Parametri">Parametri</h3> - -<p>I seguenti parametri vengono passati al metodo <code>apply</code>. <code>this</code> è legato all'handler.</p> - -<dl> - <dt><code>target</code></dt> - <dd>L'oggetto target.</dd> - <dt><code>thisArg</code></dt> - <dd>Il valore di <code>this</code> relativo alla chiamata.</dd> - <dt><code>argumentsList</code></dt> - <dd>La lista degli argomenti della chiamata.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>Il metodo <code>apply</code> può restituire qualsiasi valore.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Il metodo <code><strong>handler.apply</strong></code> è una trap per le chiamate a funzione.</p> - -<h3 id="Operazioni_intercettate">Operazioni intercettate</h3> - -<p>Questa trap può intercettare le seguenti operazioni:</p> - -<ul> - <li><code>proxy(...args)</code></li> - <li>{{jsxref("Function.prototype.apply()")}} e {{jsxref("Function.prototype.call()")}}</li> - <li>{{jsxref("Reflect.apply()")}}</li> -</ul> - -<h3 id="Invarianti">Invarianti</h3> - -<p>Se le seguenti invarianti non sono rispettate il proxy emetterà un TypeError:</p> - -<ul> - <li>Lo stesso <code>target</code> deve essere un oggetto richiamabile, cioè deve essere un oggetto funzione.</li> -</ul> - -<h2 id="Esempi">Esempi</h2> - -<p>Il codice seguente intercetta una chiamata a funzione.</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<div> -<div class="hidden">La tabella di compatibilità su questa pagina è generata a partire da dati strutturati. Se vuoi contribuire ai dati, fai un check out da <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e mandaci una pull request.</div> - -<p>{{Compat("javascript.builtins.Proxy.handler.apply")}}</p> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Proxy")}}</li> - <li>{{jsxref("Proxy.handler", "handler")}}</li> - <li>{{jsxref("Function.prototype.apply")}}</li> - <li>{{jsxref("Function.prototype.call")}}</li> - <li>{{jsxref("Reflect.apply()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/proxy/proxy/index.html b/files/it/web/javascript/reference/global_objects/proxy/proxy/index.html deleted file mode 100644 index 695cf4ce22..0000000000 --- a/files/it/web/javascript/reference/global_objects/proxy/proxy/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Proxy handler -slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy -tags: - - ECMAScript 2015 - - JavaScript - - NeedsTranslation - - Proxy - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy -translation_of_original: Web/JavaScript/Reference/Global_Objects/Proxy/handler -original_slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler ---- -<div>{{JSRef}}</div> - -<p>The proxy's handler object is a placeholder object which contains traps for {{jsxref("Proxy", "proxies", "", 1)}}.</p> - -<h2 id="Methods">Methods</h2> - -<p>All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.</p> - -<dl> - <dt>{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}</dt> - <dd>A trap for {{jsxref("Object.getPrototypeOf")}}.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}</dt> - <dd>A trap for {{jsxref("Object.setPrototypeOf")}}.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}</dt> - <dd>A trap for {{jsxref("Object.isExtensible")}}.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}</dt> - <dd>A trap for {{jsxref("Object.preventExtensions")}}.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}</dt> - <dd>A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}</dt> - <dd>A trap for {{jsxref("Object.defineProperty")}}.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}</dt> - <dd>A trap for the {{jsxref("Operators/in", "in")}} operator.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}</dt> - <dd>A trap for getting property values.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}</dt> - <dd>A trap for setting property values.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}</dt> - <dd>A trap for the {{jsxref("Operators/delete", "delete")}} operator.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}</dt> - <dd>A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}</dt> - <dd>A trap for a function call.</dd> - <dt>{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}</dt> - <dd>A trap for the {{jsxref("Operators/new", "new")}} operator.</dd> -</dl> - -<p>Some non-standard traps are <a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#Proxy">obsolete and have been removed</a>.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td>The <code>enumerate</code> handler has been removed.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.Proxy.handler")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Proxy")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/proxy/revocable/index.html b/files/it/web/javascript/reference/global_objects/proxy/revocable/index.html deleted file mode 100644 index 5039f6fa07..0000000000 --- a/files/it/web/javascript/reference/global_objects/proxy/revocable/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Proxy.revocable() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/revocable -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/revocable -original_slug: Web/JavaScript/Reference/Global_Objects/Proxy/revocabile ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>Proxy.revocable()</strong></code> è usato per creare un oggetto {{jsxref("Proxy")}} revocabile.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">Proxy.revocable(target, handler); -</pre> - -<h3 id="Parametri">Parametri</h3> - -<div>{{ Page("it/docs/Web/JavaScript/Reference/Global_Objects/Proxy", "Parametri") }}</div> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Un nuovo oggetto <code>Proxy</code> revocabile.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Un <code>Proxy</code> revocabile è un oggetto con le seguenti due proprietà <code>{proxy: proxy, revoke: revoke}</code>.</p> - -<dl> - <dt><code>proxy</code></dt> - <dd>L'oggetto Proxy creato con <code>new Proxy(target, handler)</code>.</dd> - <dt><code>revoke</code></dt> - <dd>Una funzione che non richiede argomenti per disattivare il <code>proxy</code>.</dd> -</dl> - -<p>Se la funzione <code>revoke()</code> 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 <code>revoke()</code> non avranno effetto.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-proxy.revocable', 'Proxy Revocation Functions')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-proxy.revocable', 'Proxy Revocation Functions')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_tra_Browser">Compatibilità tra Browser</h2> - - - -<p>{{Compat("javascript.builtins.Proxy.revocable")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Proxy")}}</li> -</ul> 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 deleted file mode 100644 index 367507d3d5..0000000000 --- a/files/it/web/javascript/reference/global_objects/set/entries/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Set.prototype.entries() -slug: Web/JavaScript/Reference/Global_Objects/Set/entries -translation_of: Web/JavaScript/Reference/Global_Objects/Set/entries ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>entries()</strong></code> restituisce un novo oggetto <code>Iterator</code> che contiene<strong> un array di <code>[valore, valore]</code></strong> per ciascun elemento nell'oggetto <code>Set</code>, nell'ordine con cui sono stati inseriti. Per gli oggetti di tipo <code>Set</code> non esiste alcuna <code>chiave</code> come per gli oggetti di tipo <code>Map</code>. Comunque, per mantenere le API simili a quelle dell'oggetto <code>Map</code>, per ciascun <em>elemento</em> dell'array viene utilizzato <em>value</em> anche per la <em>chiave</em>, perciò viene restituito un array <code>[valore, valore]</code>.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><em>mySet</em>.entries()</code></pre> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Un nuovo oggetto <code>Iterator</code> che contiene un array di <code>[valore, valore]</code> per ciascun elemento nell'oggetto <code>Set</code>, nell'ordine con cui sono stati inseriti.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Uso_di_entries()">Uso di <code>entries()</code></h3> - -<pre class="brush:js">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"] -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-set.prototype.entries', 'Set.prototype.entries')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-set.prototype.entries', 'Set.prototype.entries')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>38</td> - <td>{{ CompatGeckoDesktop("24") }}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>38</td> - <td>{{ CompatGeckoMobile("24") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Set.prototype.keys()")}}</li> - <li>{{jsxref("Set.prototype.values()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/set/index.html b/files/it/web/javascript/reference/global_objects/set/index.html deleted file mode 100644 index c8de5d83f6..0000000000 --- a/files/it/web/javascript/reference/global_objects/set/index.html +++ /dev/null @@ -1,394 +0,0 @@ ---- -title: Set -slug: Web/JavaScript/Reference/Global_Objects/Set -translation_of: Web/JavaScript/Reference/Global_Objects/Set ---- -<div>{{JSRef}}</div> - -<div>L'oggetto <strong>Set</strong> permette di memorizzare valori <em>unici </em>di qualunque tipo, che siano {{Glossary("Primitive", "valori primitivi")}} o riferimenti ad oggetti.</div> - -<div> </div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox">new Set([iterabile]);</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt>iterabile</dt> - <dd>Se un <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">oggetto iterabile</a> è passato, tutti i suoi elementi saranno aggiunti al nuovo Set. null viene trattato come undefined.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Gli oggetti <code>Set</code> sono collezioni di valori, e possibile iterare i valori nel loro ordine di inserimento. Un valore in un <code>Set</code> può occorrere solo una volta; è quindi unico nella collezione.</p> - -<h3 id="Uguaglianza_dei_valori">Uguaglianza dei valori</h3> - -<p>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 <a href="https://code.google.com/p/v8/issues/detail?id=3069">recente nightly Chrome issue</a>, +0 e -0 sono trattati come valori identici nell'oggetto <code>Set</code>. Inoltre, <code>NaN</code> e <code>undefined</code> possono essere memorizzati nei Set. <code>NaN</code> è considerato unguale a <code>NaN</code> (anche se <code>NaN</code> !== <code>NaN</code>).</p> - -<h2 id="Proprietà">Proprietà</h2> - -<dl> - <dt><code>Set.size</code></dt> - <dd>Il valore della proprietà <strong><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">size </span></font></strong>è 0. </dd> - <dt>{{jsxref("Set.@@species", "get Set[@@species]")}}</dt> - <dd>Il costruttore della funzione che viene usato per creare oggetti derivati.</dd> - <dt>{{jsxref("Set.prototype")}}</dt> - <dd>Rappresenta il prototipo per il costruttore del <code>Set</code>. Consente l'aggiunta di proprietà a tutti gli oggetti <code>Set</code>.</dd> -</dl> - -<h2 id="Instanze_Set"><code>Instanze Set</code></h2> - -<p>Tutte le instanze di <code>Set</code> ereditano da {{jsxref("Set.prototype")}}.</p> - -<h3 id="Proprietà_2">Proprietà</h3> - -<p>{{page('it-IT/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}</p> - -<h3 id="Methods">Methods</h3> - -<p>{{page('it-IT/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Uso_dell'oggetto_Set">Uso dell'oggetto <code>Set</code></h3> - -<pre class="brush: js">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 -</pre> - -<h3 id="Iterando_oggetti_Set">Iterando oggetti Set</h3> - -<pre class="brush: js">// 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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a>) -var myArr = [v for (v of mySet)]; // [1, "some text"] -// Alternativa (con <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">Array.from</a>) -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</pre> - -<h3 id="Relazione_con_gli_oggetti_Array">Relazione con gli oggetti <code>Array</code></h3> - -<pre class="brush: js">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</pre> - -<h2 id="Specifica">Specifica</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-set-objects', 'Set')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td> - <p>{{ CompatChrome(38) }} [1]</p> - </td> - <td>{{ CompatGeckoDesktop("13") }}</td> - <td>{{ CompatIE("11") }}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(iterable)</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>{{ CompatGeckoDesktop("13") }}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>iterable</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{ CompatGeckoDesktop("17") }}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Set.clear()</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("19")}}</td> - <td>{{ CompatIE("11") }}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Set.keys(), Set.values(), Set.entries()</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("24")}}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Set.forEach()</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("25")}}</td> - <td>{{ CompatIE("11") }}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td>Value equality for -0 and 0</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoDesktop("29")}}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(null)</code></td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td>Monkey-patched <code>add()</code> in Constructor</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Set[@@species]</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoDesktop("41")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Set()</code> without <code>new</code> throws</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoDesktop("42")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(38)}} [1]</td> - <td>{{ CompatGeckoMobile("13") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(iterable)</code></td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(38)}}</td> - <td>{{ CompatGeckoMobile("13") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>iterable</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{ CompatGeckoMobile("17") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Set.clear()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("19")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Set.keys(), Set.values(), Set.entries()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("24")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Set.forEach()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("25")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td>Value equality for -0 and 0</td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("29")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(null)</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td>Monkey-patched <code>add()</code> in Constructor</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Set[@@species]</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("41")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - <tr> - <td><code>Set()</code> without <code>new</code> throws</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("42")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] La caratteristica è disponibile come opzione da Chrome 31. In <code>chrome://flags</code>, attivare la voce “Enable Experimental JavaScript”.</p> - -<h2 id="Guarda_pure">Guarda pure</h2> - -<ul> - <li>{{jsxref("Map")}}</li> - <li>{{jsxref("WeakMap")}}</li> - <li>{{jsxref("WeakSet")}}</li> -</ul> 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 deleted file mode 100644 index e662f3d62d..0000000000 --- a/files/it/web/javascript/reference/global_objects/set/values/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Set.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Set/values -translation_of: Web/JavaScript/Reference/Global_Objects/Set/values ---- -<div>{{JSRef}}</div> - -<p>Il metodo <code><strong>values()</strong></code> restituisce un nuovo oggetto di tipo <code><strong>Iterator</strong></code> che contiene tutti i valori presenti nell'oggetto <code>Set</code>, nell'ordine con cui sono stati inseriti.</p> - -<p>Il metodo <strong><code>keys()</code></strong> è un alias per questo metodo (in modo da mantenere api simili all'oggetto {{jsxref("Map")}}); si comporta esattamente allo stesss modo e restiuisce i <strong>valori</strong> contenuti nell'oggetto <code>Set</code>.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><em>mySet</em>.values(); -</code></pre> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Un nuovo oggetto di tipo <code><strong>Iterator</strong></code> che contiene tutti i valori presenti nell'oggetto <code>Set</code>, nell'ordine con cui sono stati inseriti.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Uso_di_values()">Uso di <code>values()</code></h3> - -<pre class="brush:js">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"</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifiche</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-set.prototype.values', 'Set.prototype.values')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-set.prototype.values', 'Set.prototype.values')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_browser">Compatibilità browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>38</td> - <td>{{CompatGeckoDesktop("24")}}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>38</td> - <td>{{ CompatGeckoMobile("24") }}</td> - <td>{{ CompatNo}}</td> - <td>{{ CompatNo}}</td> - <td>8</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("Set.prototype.entries()")}}</li> -</ul> 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 deleted file mode 100644 index 312cfa9713..0000000000 --- a/files/it/web/javascript/reference/global_objects/string/charat/index.html +++ /dev/null @@ -1,247 +0,0 @@ ---- -title: String.prototype.charAt() -slug: Web/JavaScript/Reference/Global_Objects/String/charAt -translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt ---- -<div>{{JSRef}}</div> - -<p><span class="seoSummary">Il metodo {{jsxref("String")}} dell'oggetto <strong><code>charAt()</code></strong> restituisce una nuova stringa che consiste nella singola unità di codice UTF-16 situata nell'offset specificato nella stringa.</span></p> - -<div>{{EmbedInteractiveExample("pages/js/string-charat.html")}}</div> - -<p class="hidden">La fonte per questo esempio interattivo è memorizzata in un repository GitHub. Se desideri contribuire al progetto di esempi interattivi, clonare <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviarci una richiesta di pull.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><em>carattere</em> = <em>str</em>.charAt(<em>indice</em>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>index</code></dt> - <dd>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.</dd> -</dl> - -<h3 id="Valore_restituito">Valore restituito</h3> - -<p>Una stringa che rappresenta il carattere (esattamente un'unità di codice UTF-16) nell'indice specificato; stringa vuota se <code>index</code> non è compreso nell'intervallo</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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 <code>stringName</code> è <code>stringName.length - 1</code>. Se l'indice che fornisci è fuori da questo intervallo, JavaScript restituisce una stringa vuota.</p> - -<p>Se non viene fornito alcun indice per <code> charAt()</code>, il valore predefinito è 0.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Visualizzazione_di_caratteri_in_posizioni_diverse_in_una_stringa">Visualizzazione di caratteri in posizioni diverse in una stringa</h3> - -<p>Nell'esempio seguente vengono visualizzati caratteri in posizioni diverse nella stringa <code> "Brave new world"</code>:</p> - -<pre class="brush: js">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) + "'"); -</pre> - -<p>Queste righe mostrano quanto segue:</p> - -<pre class="brush: js">//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 '' -</pre> - -<h3 id="Recupero_di_caratteri_interi">Recupero di caratteri interi</h3> - -<p>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.</p> - -<pre class="brush: js">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; -} -</pre> - -<p>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).</p> - -<pre class="brush: js">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]; -} -</pre> - -<h3 id="Correggere_charAt()_per_supportare_caratteri_non-Basic-Multilingual-Plane_(BMP)">Correggere <code>charAt()</code> per supportare caratteri non-Basic-Multilingual-Plane (BMP)</h3> - -<p>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:</p> - -<pre class="brush: js">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; -} -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazioni</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_il_browser">Compatibilità con il browser</h2> - -<p class="hidden">La tabella di compatibilità in questa pagina è generata da dati strutturati. Se desideri contribuire ai dati, consulta <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una richiesta di pull.</p> - -<p>{{Compat("javascript.builtins.String.charAt")}}</p> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li>{{jsxref("String.prototype.indexOf()")}}</li> - <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> - <li>{{jsxref("String.prototype.charCodeAt()")}}</li> - <li>{{jsxref("String.prototype.codePointAt()")}}</li> - <li>{{jsxref("String.prototype.split()")}}</li> - <li>{{jsxref("String.fromCodePoint()")}}</li> - <li><a href="https://mathiasbynens.be/notes/javascript-unicode">JavaScript has a Unicode problem – Mathias Bynens</a></li> -</ul> 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 deleted file mode 100644 index 44eac8fc22..0000000000 --- a/files/it/web/javascript/reference/global_objects/string/includes/index.html +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: String.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/String/includes -translation_of: Web/JavaScript/Reference/Global_Objects/String/includes ---- -<div>{{JSRef}}</div> - -<div>Il metodo <strong><code>includes() </code></strong>verifica se una stringa ne contiene un'altra desiderata, restituendo <code>true</code> o <code>false</code> in base dell'esito della ricerca.</div> - -<div> </div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>str</var>.includes(<var>searchString</var>[, <var>position</var>])</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>searchString</code></dt> - <dd>Una stringa da cercare all'interno di una stringa.</dd> - <dt><code>position</code></dt> - <dd>Opzionale. La posizione in questa stringa. La posizione in questa stringa in cui iniziare la ricerca di searchString; il valore predefinito è 0.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p><strong><code>true</code></strong> se la stringa contiene la stringa di ricerca; altrimenti, <strong><code>false</code></strong>.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Questo metodo permette di determinare se la stringa includa o no un'altra stringa.</p> - -<h3 id="Sensitività_alle_maiuscole">Sensitività alle maiuscole</h3> - -<p>Il metodo <code>includes()</code> è sensibile alle maiuscole. Per esempio, la seguente espressione restituisce false:</p> - -<pre class="brush: js">'Blue Whale'.includes('blue'); // returns false -</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzando_includes()">Utilizzando <code>includes()</code></h3> - -<pre class="brush: js">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 -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<p>Questo metodo è stato aggiunto alla specifica ECMAScript 2015 e potrebbe essere non disponibile ancora in tutte le implementazioni di JavaScript.</p> - -<pre class="brush: js">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); - -*/</pre> - -<p> </p> - -<p> </p> - -<p> </p> - -<p> </p> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-string.prototype.includes', 'String.prototype.includes')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Definizioni inizili.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_Browser">Compatibilità Browser </h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Edge</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatChrome("41")}}</td> - <td>{{CompatGeckoDesktop("40")}}</td> - <td>{{CompatNo}}</td> - <td>14393+</td> - <td>{{CompatNo}}</td> - <td>{{CompatSafari("9")}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatGeckoMobile("40")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="String.prototype.contains">String.prototype.contains</h2> - -<p>In Firefox 18 - 39, il nome di questo metodo era <code>contains()</code>. E' stato rinominato in<code>includes()</code> in {{bug(1102219)}} a causa del seguente motivo:</p> - -<p>E' stato riportato che alcuni websites che utilizzano MooTools 1.2 non funzionavano su Firefox 17. Tale versione di MooTools controlla se <code>String.prototype.contains()</code> 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 <code>String.prototype.contains()</code> non funzioni. Come risultato, l'implementazione è stata disabilitata in Firefox 17 e <code>String.prototype.contains()</code> era disponibile nella versione successiva, in Firefox 18, quando <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=789036#c32">outreach to MooTools </a>stava conducendo al rilascio di <a href="http://mootools.net/blog/2013/02/19/mootools-1-2-6-released">MooTools version 1.2.6</a>.</p> - -<p>MooTools 1.3 forza la propria versione di <code>String.prototype.contains()</code>, così i siti web che si affidano ad essa non vanno in break. Comunque si noti che la signature di <a href="http://mootools.net/core/docs/1.3.2/Types/String#String-method:-contains">MooTools 1.3 </a>e quella di ECMAScript 2015 per questo metodo differiscono (sul secondo argomento). Più avanti , <a href="https://github.com/mootools/mootools-core/blob/master/Docs/Types/String.md#note">MooTools 1.5+ ha cambiato la signature per incontrare lo standard ES2015.</a></p> - -<p>In Firefox 48, <code>String.prototype.contains()</code> è stato rimosso. Usare <code>String.prototype.includes()</code> solamente.</p> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li>{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}</li> - <li>{{jsxref("TypedArray.prototype.includes()")}} {{experimental_inline}}</li> - <li>{{jsxref("String.prototype.indexOf()")}}</li> - <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> - <li>{{jsxref("String.prototype.startsWith()")}}</li> - <li>{{jsxref("String.prototype.endsWith()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/string/index.html b/files/it/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index 713f9a0cb4..0000000000 --- a/files/it/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,410 +0,0 @@ ---- -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 ---- -<div>{{JSRef}}</div> - -<p>L'oggetto globale "String" è un costruttore per le stringhe o una sequenza alfanumerica di caratteri.</p> - -<h2 id="Syntax">Syntax</h2> - -<p>String literals take the forms:</p> - -<pre class="syntaxbox">'string text' -"string text" -"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre> - -<p>Strings can also be created using the <code>String</code> global object directly:</p> - -<pre class="syntaxbox">String(thing)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>thing</code></dt> - <dd>Anything to be converted to a string.</dd> -</dl> - -<h3 id="Template_literals">Template literals</h3> - -<p>Starting with ECMAScript 2015, string literals can also be so-called <a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a>:</p> - -<pre class="syntaxbox">`hello world` -`hello! - world!` -`hello ${who}` -escape `<a>${who}</a>`</pre> - -<dl> -</dl> - -<h3 id="Escape_notation">Escape notation</h3> - -<p>Beside regular, printable characters, special characters can be encoded using escape notation:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Code</th> - <th scope="col">Output</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>\0</code></td> - <td>the NULL character</td> - </tr> - <tr> - <td><code>\'</code></td> - <td>single quote</td> - </tr> - <tr> - <td><code>\"</code></td> - <td>double quote</td> - </tr> - <tr> - <td><code>\\</code></td> - <td>backslash</td> - </tr> - <tr> - <td><code>\n</code></td> - <td>nuova linea</td> - </tr> - <tr> - <td><code>\r</code></td> - <td>carriage return</td> - </tr> - <tr> - <td><code>\v</code></td> - <td>vertical tab</td> - </tr> - <tr> - <td><code>\t</code></td> - <td>tab</td> - </tr> - <tr> - <td><code>\b</code></td> - <td>backspace</td> - </tr> - <tr> - <td><code>\f</code></td> - <td>form feed</td> - </tr> - <tr> - <td><code>\uXXXX</code></td> - <td>unicode codepoint</td> - </tr> - <tr> - <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> - <td>unicode codepoint {{experimental_inline}}</td> - </tr> - <tr> - <td><code>\xXX</code></td> - <td>the Latin-1 character</td> - </tr> - </tbody> -</table> - -<div class="note"> -<p>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.</p> -</div> - -<dl> -</dl> - -<h3 id="Long_literal_strings">Long literal strings</h3> - -<p>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.</p> - -<p>You can use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> operator to append multiple strings together, like this:</p> - -<pre class="brush: js">let longString = "This is a very long string which needs " + - "to wrap across multiple lines because " + - "otherwise my code is unreadable."; -</pre> - -<p>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:</p> - -<pre class="brush: js">let longString = "This is a very long string which needs \ -to wrap across multiple lines because \ -otherwise my code is unreadable."; -</pre> - -<p>Both of these result in identical strings being created.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, 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.</p> - -<h3 id="Character_access">Character access</h3> - -<p>There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:</p> - -<pre class="brush: js">return 'cat'.charAt(1); // returns "a" -</pre> - -<p>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:</p> - -<pre class="brush: js">return 'cat'[1]; // returns "a" -</pre> - -<p>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.)</p> - -<h3 id="Comparing_strings">Comparing strings</h3> - -<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</p> - -<pre class="brush: js">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.'); -} -</pre> - -<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> - -<h3 id="Distinction_between_string_primitives_and_String_objects">Distinction between string primitives and <code>String</code> objects</h3> - -<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> - -<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> 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.</p> - -<pre class="brush: js">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" -</pre> - -<p>String primitives and <code>String</code> objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</p> - -<pre class="brush: js">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" -</pre> - -<p>For these reasons, code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally authors need not worry about the distinction.</p> - -<p>A <code>String</code> object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.</p> - -<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 -</pre> - -<div class="note"><strong>Note:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a>.</div> - -<h2 id="Properties">Properties</h2> - -<dl> - <dt>{{jsxref("String.prototype")}}</dt> - <dd>Allows the addition of properties to a <code>String</code> object.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<dl> - <dt>{{jsxref("String.fromCharCode()")}}</dt> - <dd>Returns a string created by using the specified sequence of Unicode values.</dd> - <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> - <dd>Returns a string created by using the specified sequence of code points.</dd> - <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> - <dd>Returns a string created from a raw template string.</dd> -</dl> - -<h2 id="String_generic_methods"><code>String</code> generic methods</h2> - -<div class="warning"> -<p><strong>String generics are non-standard, deprecated and will get removed near future</strong>. Note that you can not rely on them cross-browser without using the shim that is provided below.</p> -</div> - -<p>The <code>String</code> instance methods are also available in Firefox as of JavaScript 1.6 (<strong>not</strong> part of the ECMAScript standard) on the <code>String</code> object for applying <code>String</code> methods to any object:</p> - -<pre class="brush: js">var num = 15; -console.log(String.replace(num, /5/, '2')); -</pre> - -<p>{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.</p> - -<p>The following is a shim to provide support to non-supporting browsers:</p> - -<pre class="brush: js">/*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]); - } -}()); -</pre> - -<h2 id="String_instances"><code>String</code> instances</h2> - -<h3 id="Properties_2">Properties</h3> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</div> - -<h3 id="Methods_2">Methods</h3> - -<h4 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h4> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</div> - -<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</div> - -<h2 id="Examples">Examples</h2> - -<h3 id="String_conversion">String conversion</h3> - -<p>It's possible to use <code>String</code> as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, as although it still normally calls the underlying <code>toString()</code>, it also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:</p> - -<pre class="brush: js">var outputStrings = []; -for (var i = 0, n = inputValues.length; i < n; ++i) { - outputStrings.push(String(inputValues[i])); -} -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-string-objects', 'String')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatChrome("1")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - <tr> - <td><code>\u{XXXXXX}</code></td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("40")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - <tr> - <td><code>\u{XXXXXX}</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("40")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{domxref("DOMString")}}</li> - <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> - <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> -</ul> 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 deleted file mode 100644 index e8653cac62..0000000000 --- a/files/it/web/javascript/reference/global_objects/string/indexof/index.html +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: String.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/String/indexOf -translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf ---- -<div>{{JSRef}}</div> - -<p>Il metodo <strong><code>indexOf()</code></strong> restituisce l'indice all'interno dell'oggetto {{jsxref("String")}} chiamante della prima occorrenza del valore specificato, avviando la ricerca su <code>fromIndex</code>. Restituisce -1 se il valore non viene trovato.</p> - -<div>{{EmbedInteractiveExample("pages/js/string-indexof.html")}}</div> - - - -<div class="note"><strong>Note:</strong> Per il metodo dell'Array, vedere {{jsxref("Array.prototype.indexOf()")}}.</div> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><var>str</var>.indexOf(<var>searchValue</var>[, <var>fromIndex</var>])</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><var>searchValue</var></dt> - <dd>Una stringa che rappresenta il valore da cercare. Se non viene fornita esplicitamente alcuna stringa, <a href="https://tc39.github.io/ecma262/#sec-tostring"><var>searchValue</var> sarà forzato a <code>"undefined"</code></a> e questo valore verrà cercato nella stringa corrente.</dd> - <dt><var>fromIndex</var> {{optional_inline}}</dt> - <dd>Un numero intero che rappresenta l'indice al quale avviare la ricerca; il valore predefinito è <code>0</code>. Per valori <code>fromIndex</code> values inferiori a <code>0</code> o maggiori di <code>str.length</code>, la ricerca inizia rispettivamente con <code>0</code> e <code>str.length</code>.</dd> -</dl> - -<h3 id="Valore_di_ritorno">Valore di ritorno</h3> - -<p>L'indice della prima occorrenza di <em>searchValue</em> o <strong>-1</strong> se non trovato.<br> - Una stringa vuota <em>searchValue</em> corrisponderà a qualsiasi indice tra <code>0</code> e <code>str.length</code>.</p> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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 <code>stringName</code> è <code>stringName.length - 1</code>.</p> - -<pre class="brush: js">'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 -</pre> - -<p>Il metodo <code>indexOf()</code> è case sensitive. Ad esempio, la seguente espressione restituisce -1:</p> - -<pre class="brush: js">'Blue Whale'.indexOf('blue'); // ritorna -1 -</pre> - -<h3 id="Controllo_delle_occorrenze">Controllo delle occorrenze</h3> - -<p>Nota che '0' non valuta <code>true</code> e '-1' non valuta <code>false</code>. Pertanto, quando si verifica se esiste una stringa specifica all'interno di un'altra stringa, il modo corretto per verificare sarebbe:</p> - -<pre class="brush: js">'Blue Whale'.indexOf('Blue') !== -1; // true -'Blue Whale'.indexOf('Bloe') !== -1; // false -</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Usare_indexOf()">Usare <code>indexOf()</code></h3> - -<p>Nell'esempio seguente viene utilizzato <code>indexOf()</code> per individuare i valori nella stringa <code>"Brave new world"</code>.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="indexOf()_e_il_case-sensitivity"><code>indexOf()</code> e il case-sensitivity</h3> - -<p>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 <code>indexOf()</code> è case sensitive, la stringa <code>"cheddar"</code> non si trova in <code>myCapString</code>, quindi il secondo metodo <code>console.log()</code> mostra -1.</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="Uso_di_indexOf()_per_contare_le_occorrenze_di_una_lettera_in_una_stringa">Uso di <code>indexOf()</code> per contare le occorrenze di una lettera in una stringa</h3> - -<p>L'esempio seguente imposta <code>count</code> sul numero di occorrenze della lettera <code>e</code> nella stringa <code>str</code>:</p> - -<pre class="brush: js">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 -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - - - -<p>{{Compat("javascript.builtins.String.indexOf")}}</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li>{{jsxref("String.prototype.charAt()")}}</li> - <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> - <li>{{jsxref("String.prototype.includes()")}}</li> - <li>{{jsxref("String.prototype.split()")}}</li> - <li>{{jsxref("Array.prototype.indexOf()")}}</li> -</ul> 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 deleted file mode 100644 index e575b777b8..0000000000 --- a/files/it/web/javascript/reference/global_objects/string/length/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: string.length -slug: Web/JavaScript/Reference/Global_Objects/String/length -translation_of: Web/JavaScript/Reference/Global_Objects/String/length ---- -<div>{{JSRef}}</div> - -<p>La proprietà <strong><code>length</code></strong> di un oggetto {{jsxref("String")}} indica la lunghezza di una stringa, in unità di codice UTF-16<span class="seoSummary">.</span></p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code><var>str</var>.length</code></pre> - -<h2 id="Descrizione">Descrizione</h2> - -<p>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 <code>length</code> “lunghezza“ non corrisponda al numero effettivo di caratteri nella stringa.</p> - -<p>ECMASCript 2016 (ed. 7) ha stabilito una lunghezza massima di <code>2^53 - 1</code> elementi. In precedenza, non è stata specificata una lunghezza massima.. </p> - -<p>Per una stringa vuota, <code>length</code> è 0.</p> - -<p>La proprietà statica <code>String.length</code> restituisce il valore 1.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Basic_usage">Basic usage</h3> - -<pre class="brush: js">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" */</pre> - -<h3 id="Assegnazione_a_length">Assegnazione a length</h3> - -<pre class="brush: js">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" */ -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazioni</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Definizione iniziale Implementato in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibili">Browser compatibili</h2> - -<p class="hidden">La tabella di compatibilità in questa pagina è generata da dati strutturati. Se desideri contribuire ai dati, consulta <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una richiesta di pull</p> - -<p>{{Compat("javascript.builtins.String.length")}}</p> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li><a href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/javascript-string-length-and-internationalizing-web-applications">JavaScript <code>String.length</code> and Internationalizing Web Applications</a></li> -</ul> 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 deleted file mode 100644 index 2d070b15cb..0000000000 --- a/files/it/web/javascript/reference/global_objects/string/raw/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: String.raw() -slug: Web/JavaScript/Reference/Global_Objects/String/raw -translation_of: Web/JavaScript/Reference/Global_Objects/String/raw ---- -<div>{{JSRef}}</div> - -<p>Il metodo statico <strong><code>String.raw()</code></strong> è una funzione di tag del modello <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">template string</a>, simile al prefisso <code>r</code> in Python o al prefisso <code>@</code> in C# per i valori letterali stringa (tuttavia c'è una differenza: vedere le spiegazioni in <a href="https://bugs.chromium.org/p/v8/issues/detail?id=5016" rel="noopener">questo numero</a> ). È usato per ottenere la stringa di stringhe di template non formattata, cioè le sostituzioni (ad esempio <font face="consolas, Liberation Mono, courier, monospace">${foo}</font>) vengono elaborate, ma gli escape (ad esempio <code>\n</code> ) non lo sono.</p> - -<h2 id="Sintassi">Sintassi</h2> - -<pre class="syntaxbox"><code>String.raw(<var>callSite</var>, <var>...substitutions</var>) -String.raw`templateString` -</code></pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>callSite</code></dt> - <dd>Oggetto del sito di chiamata template ben formato, come <code>{ raw: ['foo', 'bar', 'baz'] }</code>.</dd> - <dt><code>...substitutions</code></dt> - <dd>Contiene valori di sostituzione.</dd> - <dt><code>templateString</code></dt> - <dd>A <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">template string</a>, puoi sostituirlo opzionalmente (<code>${...}</code>).</dd> -</dl> - -<h3 id="Valore_resituto">Valore resituto</h3> - -<p>Restituisce una stringa non elaborata di un determinato Template String.</p> - -<h3 id="Eccezioni">Eccezioni</h3> - -<dl> - <dt>{{jsxref("TypeError")}}</dt> - <dd>Un oggetto {{jsxref("TypeError")}} viene generato se il primo argomento non è un oggetto formato.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Nella maggior parte dei casi, <code>String.raw()</code> 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 <a href="/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_literals">funzioni tag</a> .</p> - -<p><code>String.raw()</code> è 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.</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Utilizzo_di_String.raw()">Utilizzo di <code>String.raw()</code></h3> - -<pre class="brush: js">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. - -<code>let</code> 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 <code>`t${0}e${1}s${2}t` </code>puoi fare: -<code>String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'</code> -// Nota che la stringa 'test', è un oggetto simile ad un array -// Il seguente è equivalente a -<code>// `foo${2 + 3}bar${'Java' + 'Script'}baz` -String.raw({ - raw: ['foo', 'bar', 'baz'] -}, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'</code></pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazioni</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-string.raw', 'String.raw')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-string.raw', 'String.raw')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_il_browser">Compatibilità con il browser</h2> - -<p class="hidden">La tabella di compatibilità in questa pagina è generata da dati strutturati. Se desideri contribuire ai dati, consulta <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una richiesta di pull.</p> - -<p>{{Compat("javascript.builtins.String.raw")}}</p> - -<h2 id="Guarda_anche">Guarda anche</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/template_strings">Template strings</a></li> - <li>{{jsxref("String")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/symbol/index.html b/files/it/web/javascript/reference/global_objects/symbol/index.html deleted file mode 100644 index 5445a96009..0000000000 --- a/files/it/web/javascript/reference/global_objects/symbol/index.html +++ /dev/null @@ -1,230 +0,0 @@ ---- -title: Symbol -slug: Web/JavaScript/Reference/Global_Objects/Symbol -tags: - - ECMAScript 2015 - - ECMAScript6 - - JavaScript - - Symbol -translation_of: Web/JavaScript/Reference/Global_Objects/Symbol ---- -<div>{{JSRef}}</div> - -<p>La funzione <code>Symbol()</code> restituisce un valore di tipo <strong>symbol</strong>, 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 "<code>new Symbol()</code>". </p> - -<p>Ogni valore symbol restituito da <code>Symbol()</code> è 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: <a href="/en-US/docs/Glossary/Symbol">glossary entry for Symbol</a>.</p> - -<p>Il tipo di dati <strong>symbol</strong> è un {{Glossary("Primitive", "primitive data type")}}.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">Symbol(<em>[description]</em>)</pre> - -<h3 id="Parametri">Parametri</h3> - -<dl> - <dt><code>description</code> {{optional_inline}}</dt> - <dd>Opzionale, string. Una descrizione del symbol che può essere usata per il debug ma non per accedere al symbol stesso.</dd> -</dl> - -<h2 id="Descrizione">Descrizione</h2> - -<p>Per creare un nuovo primitive symbol, scrivere<code>Symbol()</code> con una stringa opzionale di descrizione:</p> - -<pre class="brush: js">var sym1 = Symbol(); -var sym2 = Symbol('foo'); -var sym3 = Symbol('foo'); -</pre> - -<p>Il codice sopra crea tre nuovi symbol. Notare che <code>Symbol("foo")</code> non costringe la stringa "foo" in un symbol. Esso crea un nuovo symbol ogni volta:</p> - -<pre class="brush: js">Symbol('foo') === Symbol('foo'); // false</pre> - -<p>La sintassi seguente con l'operatore {{jsxref("Operators/new", "new")}} genererà un {{jsxref("TypeError")}}:</p> - -<pre class="brush: js">var sym = new Symbol(); // TypeError</pre> - -<p>Questo previene gli autori dal creare un esplicito oggetto wrapper <code>Symbol</code> 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, <code>new Boolean</code>, <code>new String</code> e <code>new Number</code>).</p> - -<p>Se veramente si vuole creare un oggetto wrapper <code>Symbol</code> si può usare la funzione <code>Object()</code>:</p> - -<pre class="brush: js">var sym = Symbol('foo'); -typeof sym; // "symbol" -var symObj = Object(sym); -typeof symObj; // "object" -</pre> - -<h3 id="Symbols_condivisi_nel_registro_globale_dei_symbol">Symbols condivisi nel registro globale dei symbol</h3> - -<p>La sintassi vista sopra che utilizza la funzione <code>Symbol()</code> 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.</p> - -<h3 id="Cercare_le_proprietà_symbol_negli_oggetti">Cercare le proprietà symbol negli oggetti</h3> - -<p>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.</p> - -<h2 id="Proprietà">Proprietà</h2> - -<dl> - <dt><code>Symbol.length</code></dt> - <dd>Proprietà "lunghezza", il cui valore è 0.</dd> - <dt>{{jsxref("Symbol.prototype")}}</dt> - <dd>Rappresenta il prototype del costruttore <code>Symbol</code>.</dd> -</dl> - -<h3 id="Symbols_ben_noti">Symbols ben noti</h3> - -<p>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à:</p> - -<h4 id="Symbols_di_iterazione">Symbols di iterazione</h4> - -<dl> - <dt>{{jsxref("Symbol.iterator")}}</dt> - <dd>Un metodo che restituisce l'iteratore di default per un oggetto. Usato da <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for...of</code></a>.</dd> - <dt>{{jsxref("Symbol.asyncIterator")}} {{experimental_inline}}</dt> - <dd>Un metodo che restituisce l'iteratore asincrono di default per un oggetto. Usato da <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for-await-of"><code>for await of</code></a>.</dd> -</dl> - -<h4 id="Symbols_per_le_espressioni_regolari">Symbols per le espressioni regolari</h4> - -<dl> - <dt>{{jsxref("Symbol.match")}}</dt> - <dd>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()")}}.</dd> - <dt>{{jsxref("Symbol.replace")}}</dt> - <dd>Un metodo che sostituisce le sottostringhe di una stringa corrispondenti. Usato da {{jsxref("String.prototype.replace()")}}.</dd> - <dt>{{jsxref("Symbol.search")}}</dt> - <dd>Un metodo che restituisce l'indice all'interno di una stringa che corrisponde all'espressione regolare. Usato da {{jsxref("String.prototype.search()")}}.</dd> - <dt>{{jsxref("Symbol.split")}}</dt> - <dd>Un metodo che divide una stringa all'indice corrispondente ad una espressione regolare. Usato da {{jsxref("String.prototype.split()")}}.</dd> -</dl> - -<h4 id="Altri_symbols">Altri symbols</h4> - -<dl> - <dt>{{jsxref("Symbol.hasInstance")}}</dt> - <dd>Un metodo che determina se un oggetto costruttore riconosce un oggetto come propria istanza. Usato da {{jsxref("Operators/instanceof", "instanceof")}}.</dd> - <dt>{{jsxref("Symbol.isConcatSpreadable")}}</dt> - <dd>Un valore booleano indicante se un oggetto deve essere appiattito ai soui elementi array. Usato da {{jsxref("Array.prototype.concat()")}}.</dd> - <dt>{{jsxref("Symbol.unscopables")}}</dt> - <dd>An object value of whose own and inherited property names are excluded from the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/with">with</a></code> environment bindings of the associated object.</dd> - <dt>{{jsxref("Symbol.species")}}</dt> - <dd>Una funzione costruttore utilizzata per creare oggetti derivati.</dd> - <dt>{{jsxref("Symbol.toPrimitive")}}</dt> - <dd>Un metodo che converte un oggetto in un valore primitivo.</dd> - <dt>{{jsxref("Symbol.toStringTag")}}</dt> - <dd>Una stringa usata per la descizione di default di un oggetto. Usato da {{jsxref("Object.prototype.toString()")}}.</dd> -</dl> - -<h2 id="Metodi">Metodi</h2> - -<dl> - <dt>{{jsxref("Symbol.for()", "Symbol.for(key)")}}</dt> - <dd>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.</dd> - <dt>{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}</dt> - <dd>Trova una chiave symbol condivisa dal registro globale dei symbol per il symbol fornito.</dd> -</dl> - -<h2 id="Symbol_prototype"><code>Symbol</code> prototype</h2> - -<p>Tutti i simboli ereditano da {{jsxref("Symbol.prototype")}}.</p> - -<h3 id="Proprietà_2">Proprietà</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Properties')}}</p> - -<h3 id="Metodi_2">Metodi</h3> - -<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}</p> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="Using_the_typeof_operator_with_symbols">Using the <code>typeof</code> operator with symbols</h3> - -<p>L'operatore {{jsxref("Operators/typeof", "typeof")}} può aiutare ad identificare i symbol.</p> - -<pre class="brush: js">typeof Symbol() === 'symbol' -typeof Symbol('foo') === 'symbol' -typeof Symbol.iterator === 'symbol' -</pre> - -<h3 id="Conversioni_di_tipo_dei_symbol">Conversioni di tipo dei symbol</h3> - -<p>Alcune cose da notare quando si lavora con le conversioni di tipo dei symbol.</p> - -<ul> - <li>Quando si prova a convertire un symbol in un numero, un {{jsxref("TypeError")}} verrà generato<br> - (e.g. <code>+sym</code> or <code>sym | 0</code>).</li> - <li>Quando si usa l'uguaglianza non stretta, <code>Object(sym) == sym</code> restituisce <code>true.</code></li> - <li><code>Symbol("foo") + "bar"</code> lancia un {{jsxref("TypeError")}} (non si può convertire un symbol in stringa). Questo previene, ad esempio, la creazione silenziosa di un nuovo nome di proprietà stringa da un symbol.</li> - <li>La <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_conversion">"safer" <code>String(sym)</code> conversion</a> funziona come una chiamata a {{jsxref("Symbol.prototype.toString()")}} con symbol, ma notare che <code>new String(sym)</code> genererà un errore.</li> -</ul> - -<h3 id="Symbols_ed_iterazione_for...in">Symbols ed iterazione <code>for...in</code></h3> - -<p>I symbol non sono enumerabili in un'iterazione <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a>. In aggiunta, {{jsxref("Object.getOwnPropertyNames()")}} non restituirà le proprietà symbol dell'oggetto, tuttavia, si puù usare {{jsxref("Object.getOwnPropertySymbols()")}} per ottenerle.</p> - -<pre class="brush: js">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" -}</pre> - -<h3 id="Symbols_e_JSON.stringify()">Symbols e <code>JSON.stringify()</code></h3> - -<p>Le proprietà le cui chiavi sono symbol vengono completamente ignorate da <code>JSON.stringify()</code>:</p> - -<pre class="brush: js">JSON.stringify({[Symbol('foo')]: 'foo'}); -// '{}'</pre> - -<p>Per ulteriori dettagli, vedere {{jsxref("JSON.stringify()")}}.</p> - -<h3 id="Symbol_wrapper_objects_come_chiavi_per_le_proprietà">Symbol wrapper objects come chiavi per le proprietà</h3> - -<p>Quando un oggetto wrapper symbol viene usato come chiave di una proprietà, tale oggetto verrà costretto al suo wrapped symbol:</p> - -<pre class="brush: js">var sym = Symbol('foo'); -var obj = {[sym]: 1}; -obj[sym]; // 1 -obj[Object(sym)]; // still 1 -</pre> - -<h2 id="Specificazioni">Specificazioni</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specificazione</th> - <th scope="col">Stato</th> - <th scope="col">Commento</th> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-symbol-objects', 'Symbol')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.Symbol")}}</p> - -<h2 id="Vedere_anche">Vedere anche</h2> - -<ul> - <li><a href="/en-US/docs/Glossary/Symbol">Glossary: Symbol data type</a></li> - <li>{{jsxref("Operators/typeof", "typeof")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> - <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/">"ES6 In Depth: Symbols" on hacks.mozilla.org</a></li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/undefined/index.html b/files/it/web/javascript/reference/global_objects/undefined/index.html deleted file mode 100644 index d16ca712cf..0000000000 --- a/files/it/web/javascript/reference/global_objects/undefined/index.html +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: undefined -slug: Web/JavaScript/Reference/Global_Objects/undefined -translation_of: Web/JavaScript/Reference/Global_Objects/undefined ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La variabile globale <strong><code>undefined</code></strong> rappresenta il valore primitivo <span style="font-family: Consolas,Monaco,'Andale Mono',monospace;">{{Glossary("Undefined", "undefined")}}</span>. È uno dei {{Glossary("Primitive", "valori primitivi")}} di JavaScript.</p> - -<p>{{js_property_attributes(0,0,0)}}</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>undefined</code></pre> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p><code>undefined</code> è una proprietà dell'<em>oggetto globale</em>, ossia una variablie nel contesto globale. Il valore iniziale di <code>undefined</code> è il valore primitivo <span style="font-family: Consolas,Monaco,'Andale Mono',monospace;">{{Glossary("Undefined", "undefined")}}</span>. </p> - -<p>Secondo la specifica ECMAScript5, <code>undefined</code> è accessibile in sola lettura (implementato in JavaScript 1.8.5 / Firefox 4).</p> - -<p>Una variabile alla quale non è ancora stato assegnato un valore è di tipo undefined. Un metodo o una dichiarazione restituisce <code>undefined</code> se la variabile che viene valutata non ha un valore assegnato. Una funzione restituisce <code>undefined</code> se non viene restituito un altro valore.</p> - -<p>Siccome <code>undefined</code> non è una {{jsxref("Reserved_Words", "parola riservata")}}, può essere usato come <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Variables">nome di una variabile</a> in qualsiasi contesto, eccetto quello globale.</p> - -<pre class="brush: js">// logs "foo string" -(function(){ var undefined = 'foo'; console.log(undefined, typeof undefined); })(); - -// logs "foo string" -(function(undefined){ console.log(undefined, typeof undefined); })('foo'); -</pre> - -<h2 id="Esempi">Esempi</h2> - -<h3 id="undefined_e_l'uguaglianza_ristretta"><code>undefined</code> e l'uguaglianza ristretta</h3> - -<p>Puoi usare <code>undefined</code> e gli operatori "<em>strettamente uguale"</em> e "<em>strettamente diverso</em>" per determinare se ad una variabile è stato assegnato un valore. In questo codice, la variabile <code>x</code> non è definita, qundi l'istruzione <code>if</code> viene valutata vera.</p> - -<pre class="brush: js">var x; - -x === undefined; // true -</pre> - -<div class="note"><strong>Nota:</strong> Qui devono essere utilizzati gli operatori di uguaglianza stretta, perché <code>x == undefined</code> è vero anche se <code>x</code> è <code>null</code>, mentre confrontandoli con l'ugualianza stretta no. <code>null</code> e <code>undefined</code> non sono equivalenti. Vedi gli {{jsxref("Operators/Comparsion_Operators", "operatori di comparazione")}} per altri dettagli.</div> - -<h3 id="undefined_e_l'operatore_typeof"><code>undefined</code> e l'operatore <code>typeof</code></h3> - -<p>In alternativa può anche essere usato l'operatore <code>{{jsxref("Operators/typeof", "typeof")}}:</code></p> - -<pre class="brush: js">var x; - -typeof x === 'undefined'; // true -</pre> - -<p>Un motivo per cui usare l'operatore <code>{{jsxref("Operators/typeof", "typeof")}}</code> è che se la variabile non stata dichiarata non viene generato un errore.</p> - -<pre class="brush: js">// x non è ancora stata dichiarata - -typeof x === "undefined"; // viene valutata come vera, senza generare erroi - -x === undefined; // genera un ReferenceError -</pre> - -<p>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'<em>oggetto globale</em>: quindi per sapere se esiste una variabile basta controllare se esiste una proprietà nell'<em>oggetto globale</em> (per esempio usando l'operatore {{jsxref("Operators/in", "in")}} o il metodo {{jsxref("Global_Objects/Object/hasOwnProperty", "hasOwnProperty")}})</p> - -<pre class="brush: js">// x non è ancora stata dichiarata - -"x" in window; // false -window.hasOwnProperty("x"); // false - -var x = 3; - -"x" in window; // true -window.hasOwnProperty("y"); // true -</pre> - -<h3 id="undefined_e_l'operatore_void"><code>undefined</code> e l'operatore <code>void</code></h3> - -<p>Una terza alternativa è l'operatore {{jsxref("Operators/void", "<code>void</code>")}}.</p> - -<pre class="brush: js">var x; -x === void 0; // true - -// y non è ancora stata dichiarata -y === void 0; // genera un ReferenceError (a differenza di `typeof`) -</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Definizione iniziale. Implementato in JavaScript 1.3</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.1.1.3', 'undefined')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-undefined', 'undefined')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light',sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p> </p> diff --git a/files/it/web/javascript/reference/global_objects/unescape/index.html b/files/it/web/javascript/reference/global_objects/unescape/index.html deleted file mode 100644 index d3c31d5f96..0000000000 --- a/files/it/web/javascript/reference/global_objects/unescape/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: unescape() -slug: Web/JavaScript/Reference/Global_Objects/unescape -translation_of: Web/JavaScript/Reference/Global_Objects/unescape ---- -<div> -<div> -<div>{{jsSidebar("Objects")}} {{deprecated_header()}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>unescape()</code></strong>, 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 <code>unescape()</code> deprecata, è preferibile utilizzare le funzioni {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} o {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}.</p> - -<div class="note"><strong>Nota:</strong> Non usare la funzione <code>unescape()</code> per decodificare degli {{Glossary("URI")}}, usa {{jsxref("Global_Objects/decodeURI", "decodeURI()")}}.</div> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox"><code>unescape(string)</code></pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>string</code></dt> - <dd>La stringa da decodificare.</dd> -</dl> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p>La funzione <code>unescape()</code> è una proprietà dell'<em>oggetto globale</em>.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush: js">unescape("abc123"); // "abc123" -unescape("%E4%F6%FC"); // "äöü" -unescape("%u0107"); // "ć" -</pre> - -<h2 id="Specifiche">Specifiche</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specifica</th> - <th scope="col">Stato</th> - <th scope="col">Commenti</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Definizione iniziale.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-B.2.2', 'unescape')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Definita nell'appendice B, "<em>Compatibility</em>"</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-unescape-string', 'unescape')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Definita nell'appendice B, "<em>Additional ECMAScript Features for Web Browsers</em>"</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_Also" name="See_Also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> - <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> -</ul> diff --git a/files/it/web/javascript/reference/global_objects/uneval/index.html b/files/it/web/javascript/reference/global_objects/uneval/index.html deleted file mode 100644 index 965dc014b4..0000000000 --- a/files/it/web/javascript/reference/global_objects/uneval/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: uneval() -slug: Web/JavaScript/Reference/Global_Objects/uneval -translation_of: Web/JavaScript/Reference/Global_Objects/uneval ---- -<div> -<div> -<div>{{jsSidebar("Objects")}}{{Non-standard_header}}</div> -</div> -</div> - -<h2 id="Summary" name="Summary">Sommario</h2> - -<p>La funzione <strong><code>uneval()</code></strong> crea una stringa rappresentante il codice sorcente di un oggetto.</p> - -<h2 id="Syntax" name="Syntax">Sintassi</h2> - -<pre class="syntaxbox">uneval(<var>object</var>)</pre> - -<h3 id="Parameters" name="Parameters">Parametri</h3> - -<dl> - <dt><code>object</code></dt> - <dd>Una qualsiasi espressione o dichiarazione JavaScript</dd> -</dl> - -<div class="note"><strong>Nota:</strong> Questa funzione non restituisce una rappresentazione JSON valida. Usare il metodo {{jsxref("JSON.stringify()")}}</div> - -<h2 id="Description" name="Description">Descrizione</h2> - -<p><code>uneval()</code> è una funzione globale e non è associata a nessun oggetto.</p> - -<h2 id="Esempi">Esempi</h2> - -<pre class="brush:js">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" -</pre> - -<h2 id="See_also" name="See_also">Specifiche</h2> - -<p>Non fa parte di nessuna specifica.</p> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Funzionalità</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Supporto di base</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th><span style="font-family: 'Open Sans Light', sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_Also" name="See_Also">Vedi anche</h2> - -<ul> - <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> - <li>{{jsxref("JSON.stringify")}}</li> - <li>{{jsxref("JSON.parse")}}</li> - <li>{{jsxref("Object.toSource")}}</li> -</ul> |