diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
commit | da78a9e329e272dedb2400b79a3bdeebff387d47 (patch) | |
tree | e6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/it/learn/javascript | |
parent | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff) | |
download | translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2 translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip |
initial commit
Diffstat (limited to 'files/it/learn/javascript')
-rw-r--r-- | files/it/learn/javascript/building_blocks/index.html | 59 | ||||
-rw-r--r-- | files/it/learn/javascript/comefare/index.html | 291 | ||||
-rw-r--r-- | files/it/learn/javascript/first_steps/cosa_è_andato_storto/index.html | 253 | ||||
-rw-r--r-- | files/it/learn/javascript/first_steps/index.html | 68 | ||||
-rw-r--r-- | files/it/learn/javascript/first_steps/variabili/index.html | 337 | ||||
-rw-r--r-- | files/it/learn/javascript/index.html | 63 | ||||
-rw-r--r-- | files/it/learn/javascript/oggetti/basics/index.html | 242 | ||||
-rw-r--r-- | files/it/learn/javascript/oggetti/index.html | 51 | ||||
-rw-r--r-- | files/it/learn/javascript/oggetti/json/index.html | 345 |
9 files changed, 1709 insertions, 0 deletions
diff --git a/files/it/learn/javascript/building_blocks/index.html b/files/it/learn/javascript/building_blocks/index.html new file mode 100644 index 0000000000..9b7bed94d3 --- /dev/null +++ b/files/it/learn/javascript/building_blocks/index.html @@ -0,0 +1,59 @@ +--- +title: JavaScript building blocks +slug: Learn/JavaScript/Building_blocks +tags: + - Article + - Assessment + - Beginner + - CodingScripting + - Conditionals + - Functions + - Guide + - Introduction + - JavaScript + - Landing + - Loops + - Module + - NeedsTranslation + - TopicStub + - events + - 'l10n:priority' +translation_of: Learn/JavaScript/Building_blocks +--- +<div>{{LearnSidebar}}</div> + +<div>In questo modulo, continueremo con la copertura di tutte le funzionalità fondamentali di Javascript, rivolgendo la nostra attenzione ai tipi di blocco più comuni come istruzioni condizionali, loop, funzioni ed eventi. Avrai già visto queste cose nel corso, ma solo di passaggio -- qui ne discuteremo esplicitamente.</div> + +<h2 id="Prerequisiti">Prerequisiti</h2> + +<p>Prima di iniziare questo modulo, dovresti avere un po' di familiarità con le basi di <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">HTML</a> e <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">CSS</a>, e dovresti anche aver lavorato nei moduli precedenti, <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a>.</p> + +<div class="note"> +<p><strong>Nota</strong>: Se stai lavorantdo su un computer/tablet/altri dispositivi dove non hai la possibilità di creare i tuoi file, potresti provare (la maggior parte) degli esempi di codice in un programma di coding online come <a href="http://jsbin.com/">JSBin</a> opp <a href="https://thimble.mozilla.org/">Thimble</a>.</p> +</div> + +<h2 id="Guide">Guide</h2> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Prendi decisioni nel tuo codice — conditionals</a></dt> + <dd>In ogni linguaggio di programmazione, il codice necessita di prendere decisioni ed eseguire azioni di conseguenza a seconda dei diversi input. Per esempio, in un gioco, se le vite del giocatore sono 0, allora la partita termina. In un'app meteo, se viene aperta al mattino, verrà mostrata una figura dell'alba e se è notte una relativa a stelle e luna. In questo articolo esploreremo come funzionano le strutture condizionali in JavaScript</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Cicli di codice (loop)</a></dt> + <dd>A volte è necessario svolgere la stessa attività più di una volta di seguito. Ad esempi, guardando una lista di nomi. Nella programmazione i loop svolgono questo lavoro molto bene. Qui vedremo la struttura dei loop in JavaScript</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Funzioni — blocchi di codice riusabile</a></dt> + <dd>Un altro concetto essenziale nel coding sono le <strong>funzioni</strong>. Le <strong>Funzioni</strong> ti consento di memorizzare un pezzo di codice che esegue una singola attività all'interno di un blocco definito e quindi richiamare il codice ogni volta che ne hai bisogno usando un singolo breve comando — invece di dover scrivere lo stesso codice più volte. In questo articolo esploreremo i concetti fondamentali dietro funzioni come la sistassi di base, come invocare e definire funzioni, ambito e parametri.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Costruisci la tua funzione</a></dt> + <dd>Con la maggior parte della teoria essenziale trattata in precedenza, questo articolo offre un'esperienza più pratica. Qui farai un po' di pratica con la creazione della tua funzione personalizzata. Lungo la strada, spiegheremo anche alcuni ulteriori dettagli utili su come gestire le funzioni.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">Valori di ritorno delle funzioni</a></dt> + <dd>L'ultimo concetti essenziale che devi sapere sulle funzioni è il tipo di ritorno. Alcune funzioni non ritornano un valore utile dopo l'esecuzione, ma altre lo fanno. É importante capire quali sono i loro valori, come utilizzarli e come fare in modo che le tue funzioni personalizzate restituiscano valori utili</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Introduzione agli eventi</a></dt> + <dd>Gli eventi sono azioni o occorrenze che si verificano nel sistema che si sta programmando, il sistema ti informa in modo che tu possa rispondere in qualche modo se lo desideri. Ad esempio se l'utente fa click su un pulsante in una pagina Web, è possibile che si desideri rispondere a tale azione visualizzando una casella di informazioni. In quest'ultimo articolo discuteremo alcuni concetti importanti relativi agli eventi e vedremo come funzionano nei browser.</dd> +</dl> + +<h2 id="Valutazioni">Valutazioni</h2> + +<p>La seguente valutazione metterà alla prova la tua comprensione dei principi di base di JavaScript trattati nelle guide sopra.</p> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery">Galleria di immagini (carousel)</a></dt> + <dd>Ora che abbiamo esaminati i blocchi fondamentali di JavaScript, testeremo la tua conoscenza dei loop, funzioni, condizioni ed eventi creando un oggetto abbastanza comune che vedrai su molti siti Web: una galleria di immagini basata su JavaScript.</dd> +</dl> diff --git a/files/it/learn/javascript/comefare/index.html b/files/it/learn/javascript/comefare/index.html new file mode 100644 index 0000000000..275eb0cf8d --- /dev/null +++ b/files/it/learn/javascript/comefare/index.html @@ -0,0 +1,291 @@ +--- +title: Risolvere problematiche frequenti nel tuo codice JavaScript +slug: Learn/JavaScript/Comefare +tags: + - Principianti + - imparare +translation_of: Learn/JavaScript/Howto +--- +<div>R{{LearnSidebar}}</div> + +<p class="summary">I link seguenti indicano soluzioni a problematiche frequenti in cui puoi imbatterti quando programmi in javaScript.</p> + +<h2 id="Errori_comuni_dei_principianti">Errori comuni dei principianti</h2> + +<h3 id="Ortografia_corretta">Ortografia corretta</h3> + +<p>Se il tuo codice non funziona e/o il browser segnala che qualcosa non è definito, controlla di aver scritto tutti i tuoi nomi di variabili, nomi di funzioni, etc. correttamente.</p> + +<p>Alcune comuni funzioni built-in del browser che causano problemi sono: </p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Corretto</th> + <th scope="col">Sbagliato</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>getElementsByTagName()</code></td> + <td><code>getElementbyTagName()</code></td> + </tr> + <tr> + <td><code>getElementsByName()</code></td> + <td><code>getElementByName()</code></td> + </tr> + <tr> + <td><code>getElementsByClassName()</code></td> + <td><code>getElementByClassName()</code></td> + </tr> + <tr> + <td><code>getElementById()</code></td> + <td><code>getElementsById()</code></td> + </tr> + </tbody> +</table> + +<h3 id="Posizione_del_punto_e_virgola">Posizione del punto e virgola</h3> + +<p>Devi assicurarti di non aver posizionato il punto e virgola nel posto sbagliato, ad esempio :</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Corretto</th> + <th scope="col">Sbagliato</th> + </tr> + <tr> + <td><code>elem.style.color = 'red';</code></td> + <td><code>elem.style.color = 'red;'</code></td> + </tr> + </thead> +</table> + +<h3 id="Funzioni">Funzioni</h3> + +<p>Ci sono alcune cose che possono andare storte con le funzioni.</p> + +<p>Uno degli errori più comuni è dichiarare la funzione ma non chiamarla da nessuna parte. Per esempio:</p> + +<pre class="brush: js">function myFunction() { + alert('This is my function.'); +};</pre> + +<p>Questo codice non farà nulla, a meno che non venga chiamato con la seguente istruzione:</p> + +<pre class="brush: js">myFunction();</pre> + +<h4 id="Ambito_scope_della_funzione">Ambito (scope) della funzione</h4> + +<p>Ricorda che le <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Function_scope_and_conflicts">funzioni hanno il loro specifico ambito (scope)</a> — non è possibile accedere ad una variabile definita all'interno di una funzione al di fuori di essa, a meno di dichiararla globalmente (ossia fuori da ogni funzione), oppure <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">restituire il valore (return)</a> dalla funzione stessa.</p> + +<h4 id="Eseguire_codice_posto_dopo_un_istruzione_return">Eseguire codice posto dopo un istruzione return</h4> + +<p>Ricordati anche che quando incontra l'istruzione return, l'interprete JavaScript esce dalla funzione — nessun codice all'interno della funzione verrà eseguito dopo l'istruzione return.</p> + +<p>Infatti, alcuni browsers (come Firefox) ti daranno un messaggio di errore nella console dello sviluppatore se hai inserito codice dopo un'istruzione return. Firefox restituirà "unreachable code after return statement" (codice irraggiungibile dopo l'istruzione return).</p> + +<h3 id="Notazione_per_gli_oggetti_opposto_al_normale_assegnamento">Notazione per gli oggetti opposto al normale assegnamento</h3> + +<p>Quando fai un normale assegnamento in JavaScript, usi un singolo simbolo di uguale, ad es. :</p> + +<pre class="brush: js">const myNumber = 0;</pre> + +<p>Con gli <a href="/en-US/docs/Learn/JavaScript/Objects">Oggetti</a> occorre invece prestare attenzione alla corretta sintassi. L'oggetto deve essere definito delimitandolo con parentesi graffe, i nomi dei membri devono essere separati dai loro valori con i due punti e i membri tra loro da virgole. Per esempio:</p> + +<pre class="brush: js">const myObject = { + name: 'Chris', + age: 38 +}</pre> + +<h2 id="Definizioni_Base">Definizioni Base</h2> + +<div class="column-container"> +<div class="column-half"> +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#A_high-level_definition">Cos'è JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#What_is_a_variable">Cos'è una variabile?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Cosa sono le stringhe?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#What_is_an_Array">Cos'è un array?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Cos'è un ciclo?</a></li> +</ul> +</div> + +<div class="column-half"> +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Cos'è una funzione?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Cos'è un evento?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Object_basics">Cos'è un oggetto?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#No_really_what_is_JSON">Cos'è il formato JSON?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction#What_are_APIs">Cos'è una web API?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#The_document_object_model">Cos'è il DOM?</a></li> +</ul> +</div> +</div> + +<h2 id="Casi_base_duso">Casi base d'uso</h2> + +<div class="column-container"> +<div class="column-half"> +<h3 id="Generali">Generali</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#How_do_you_add_JavaScript_to_your_page">Come aggiungi JavaScript alla tua pagina?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#Comments">Come aggiungi commenti al tuo codice JavaScript?</a></li> +</ul> + +<h3 id="Variabili">Variabili</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#Declaring_a_variable">Come dichiari una variabile?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#Initializing_a_variable">Come inizializzi una variabile con un valore?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#Updating_a_variable">Come aggiorni il valore di una variabile?</a> (vedi anche <a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Assignment_operators">Operatori di assegnamento</a>)</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#Variable_types">Quali sono i tipi di dato in JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#Loose_typing">Cosa significa 'debolmente tipizzato'?</a></li> +</ul> + +<h3 id="Tipi_di_dati_numerici">Tipi di dati numerici</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Types_of_numbers">Che tipi di numeri tratti nel tuo sviluppo web?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Arithmetic_operators">Come fare matematica di base in JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Operator_precedence">Quali sono le regole di precedenza degli operatori e come sono gestite in JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Increment_and_decrement_operators">Come incrementi e decrementi valori in JavaScript?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math#Comparison_operators">Come confronti i valori in JavaScript?</a> (ad es. vedere qual'è il più grande oppure se un valore è uguale ad un altro).</li> +</ul> + +<h3 id="Stringhe">Stringhe</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Creating_a_string">Come crei una stringa in JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Single_quotes_versus_double_quotes">Devi usare singoli o doppi apici?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Escaping_characters_in_a_string">Come rappresenti i caratteri di escape nelle stringhe?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Concatenating_strings">Come unisci le stringhe tra loro?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Numbers_versus_strings">Puoi unire stringhe con numeri?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Finding_the_length_of_a_string">Come trovi la lunghezza di una stringa?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Retrieving_a_specific_string_character">Come trovi quale carattere occupa una certa posizione in una stringa?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Finding_a_substring_inside_a_string_and_extracting_it">Come trovi ed estrai una data sottostringa da una stringa?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Changing_case">Come cambi minuscole/maiuscole in una stringa?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Updating_parts_of_a_string">Come sostituisci una data sottostringa con un'altra?</a></li> +</ul> +</div> + +<div class="column-half"> +<h3 id="Arrays">Arrays</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Creating_an_array">Come crei un array?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Accessing_and_modifying_array_items">Come accedi e modifichi gli elementi di un array?</a> (include arrays multidimensionali)</li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Finding_the_length_of_an_array">Come trovi la lunghezza di un array?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Adding_and_removing_array_items">Come aggiungi e rimuovi elementi di un array?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Converting_between_strings_and_arrays">Come dividi una stringa in elementi di un array, o unisci elementi di un array a costituire una stringa?</a></li> +</ul> + +<h3 id="Debugging_JavaScript">Debugging JavaScript</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong#Types_of_error">What are the basic types of error?</a></li> + <li><a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">What are browser developer tools, and how do you access them?</a></li> + <li><a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#The_Console_API">How do you log a value to the JavaScript console?</a></li> + <li><a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#Using_the_JavaScript_debugger">How do you use breakpoints and other JavaScript debugging features?</a></li> +</ul> + +<p>For more information on JavaScript debugging, see <a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript">Handling common JavaScript problems</a>. Also, see <a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong#Other_common_errors">Other common errors</a> for a description of common errors.</p> + +<h3 id="Making_decisions_in_code">Making decisions in code</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">How do you execute different blocks of code, depending on a variable's value or other condition?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#if_..._else_statements">How do you use if ...else statements?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#Nesting_if_..._else">How do you nest one decision block inside another?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#Logical_operators_AND_OR_and_NOT">How do you use AND, OR, and NOT operators in JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#switch_statements">How do you conveniently handle a large number of choices for one condition?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#Ternary_operator">How do you use a ternary operator to make a quick choice between two options based on a true or false test?</a></li> +</ul> + +<h3 id="Loopingiteration">Looping/iteration</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">How do you run the same bit of code over and over again?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#Exiting_loops_with_break">How do you exit a loop before the end if a certain condition is met?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#Skipping_iterations_with_continue">How do you skip to the next iteration of a loop if a certain condition is met?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#while_and_do_..._while">How do you use while and do ... while loops?</a></li> + <li>How do you iterate over the elements in an array?</li> + <li>How do you iterate over the elements in a multidimensional array?</li> + <li>How do you iterate over the members in an object?</li> + <li>How do you iterate over the members of an object nested inside an array?</li> +</ul> +</div> +</div> + +<h2 id="Intermediate_use_cases">Intermediate use cases</h2> + +<div class="column-container"> +<div class="column-half"> +<h3 id="Functions">Functions</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Built-in_browser_functions">How do you find functions in the browser?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Functions_versus_methods">What is the difference between a function and a method?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">How do you create your own functions?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Invoking_functions">How do you run (call, or invoke) a function?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Anonymous_functions">What is an anonymous function?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Function_parameters">How do you specify parameters (or arguments) when invoking a function?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Function_scope_and_conflicts">What is function scope?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">What are return values, and how do you use them?</a></li> +</ul> + +<h3 id="Objects">Objects</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Object_basics">How do you create an object?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Dot_notation">What is dot notation?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation">What is bracket notation?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Setting_object_members">How do you get and set the methods and properties of an object?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#What_is_this">What is <code>this</code>, in the context of an object?</a></li> + <li><a href="/docs/Learn/JavaScript/Objects/Object-oriented_JS#Object-oriented_programming_from_10000_meters">What is object-oriented programming?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS#Constructors_and_object_instances">What are constructors and instances, and how do you create them?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS#Other_ways_to_create_object_instances">What different ways are there to create objects in JavaScript?</a></li> +</ul> + +<h3 id="JSON">JSON</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#JSON_structure">How do you structure JSON data, and read it from JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#Loading_our_JSON">How can you load a JSON file into a page?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#Converting_between_objects_and_text">How do you convert a JSON object to a text string, and back again?</a></li> +</ul> +</div> + +<div class="column-half"> +<h3 id="Events">Events</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_handler_properties">What are event handlers and how do you use them?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_don%27t_use_these">What are inline event handlers?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#addEventListener()_and_removeEventListener()">What does the <code>addEventListener()</code> function do, and how do you use it?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#What_mechanism_should_I_use">Which mechanism should I use to add event code to my web pages?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_objects">What are event objects, and how do you use them?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Preventing_default_behaviour">How do you prevent default event behaviour?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture">How do events fire on nested elements? (event propagation, also related — event bubbling and capturing)</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation">What is event delegation, and how does it work?</a></li> +</ul> + +<h3 id="Object-oriented_JavaScript">Object-oriented JavaScript</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">What are object prototypes?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes#The_constructor_property">What is the constructor property, and how can you use it?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes#Modifying_prototypes">How do you add methods to the constructor?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance">How do you create a new constructor that inherits its members from a parent constructor?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance#Object_member_summary">When should you use inheritance in JavaScript?</a></li> +</ul> + +<h3 id="Web_APIs">Web APIs</h3> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#Active_learning_Basic_DOM_manipulation">How do you manipulate the DOM (e.g. adding or removing elements) using JavaScript?</a></li> +</ul> +</div> +</div> diff --git a/files/it/learn/javascript/first_steps/cosa_è_andato_storto/index.html b/files/it/learn/javascript/first_steps/cosa_è_andato_storto/index.html new file mode 100644 index 0000000000..1fa4343de8 --- /dev/null +++ b/files/it/learn/javascript/first_steps/cosa_è_andato_storto/index.html @@ -0,0 +1,253 @@ +--- +title: Cosa è andato storto? Problemi con Javacript +slug: Learn/JavaScript/First_steps/Cosa_è_andato_storto +translation_of: Learn/JavaScript/First_steps/What_went_wrong +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">Quando abbiamo realizzato il gioco "Indovina il numero" nell'articole precedente, potresti esserti accorto che non funziona. Niente paura — questo articolo mira ad aiutarti e non farti strappare i capelli per tali problemi, fornendoti alcuni semplici aiuti su come trovare e correggere gli errori in JavaScript .</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerequisites:</th> + <td>Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.</td> + </tr> + <tr> + <th scope="row">Objective:</th> + <td>To gain the ability and confidence to start fixing simple problems in your own code.</td> + </tr> + </tbody> +</table> + +<h2 id="Types_of_error">Types of error</h2> + +<p>Generally speaking, when you do something wrong in code, there are two main types of error that you'll come across:</p> + +<ul> + <li><strong>Syntax errors</strong>: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!</li> + <li><strong>Logic errors</strong>: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn't a resulting error message to direct you to the source of the error.</li> +</ul> + +<p>Okay, so it's not quite <em>that</em> simple — there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We'll look at both of these types going forward.</p> + +<h2 id="An_erroneous_example">An erroneous example</h2> + +<p>To get started, let's return to our number guessing game — except this time we'll be exploring a version that has some deliberate errors introduced. Go to Github and make yourself a local copy of <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">number-game-errors.html</a> (see it <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">running live here</a>).</p> + +<ol> + <li>To get started, open the local copy inside your favourite text editor, and your browser.</li> + <li>Try playing the game — you'll notice that when you press the "Submit guess" button, it doesn't work!</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: You might well have your own version of the game example that doesn't work, which you might want to fix! We'd still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example.</p> +</div> + +<p>At this point, let's consult the developer console to see if we can see any syntax errors, then try to fix them. You'll learn how below.</p> + +<h2 id="Fixing_syntax_errors">Fixing syntax errors</h2> + +<p>Earlier on in the course we got you to type some simple JavaScript commands into the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a> (if you can't remember how to open this in your browser, follow the previous link to find out how). What's even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser's JavaScript engine. Now let's go hunting.</p> + +<ol> + <li>Go to the tab that you've got <code>number-game-errors.html</code> open in, and open your JavaScript console. You should see an error message along the following lines: <img alt="" src="https://mdn.mozillademos.org/files/13496/not-a-function.png" style="display: block; margin: 0 auto;"></li> + <li>This is a pretty easy error to track down, and the browser gives you several useful bits of information to help you out (the screenshot above is from Firefox, but other browsers provide similar information). From left to right, we've got: + <ul> + <li>A red "x" to indicate that this is an error.</li> + <li>An error message to indicate what's gone wrong: "TypeError: guessSubmit.addeventListener is not a function"</li> + <li>A "Learn More" link that links through to an MDN page that explains what this error means in huge amounts of detail.</li> + <li>The name of the JavaScript file, which links through to the Debugger tab of the devtools. If you follow this link, you'll see the exact line where the error is highlighted.</li> + <li>The line number where the error is, and the character number in that line where the error is first seen. In this case, we've got line 86, character number 3.</li> + </ul> + </li> + <li>If we look at line 86 in our code editor, we'll find this line: + <pre class="brush: js">guessSubmit.addeventListener('click', checkGuess);</pre> + </li> + <li>The error message says "guessSubmit.addeventListener is not a function", so we've probably spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn <em>name-of-feature</em>" on your favourite search engine. Here's a shortcut to save you some time in this instance: <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code>.</li> + <li>So, looking at this page, the error appears to be that we've spelled the function name wrong! Remember that JavaScript is case sensitive, so any slight difference in spelling or casing will cause an error. Changing <code>addeventListener</code> to <code>addEventListener</code> should fix this. Do this now.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function">TypeError: "x" is not a function</a> reference page for more details about this error.</p> +</div> + +<h3 id="Syntax_errors_round_two">Syntax errors round two</h3> + +<ol> + <li>Save your page and refresh, and you should see the error has gone.</li> + <li>Now if you try to enter a guess and press the Submit guess button, you'll see ... another error! <img alt="" src="https://mdn.mozillademos.org/files/13498/variable-is-null.png" style="display: block; margin: 0 auto;"></li> + <li>This time the error being reported is "TypeError: lowOrHi is null", on line 78. + <div class="note"><strong>Note</strong>: <code><a href="/en-US/docs/Glossary/Null">Null</a></code> is a special value that means "nothing", or "no value". So <code>lowOrHi</code> has been declared and initialised, but not with any meaningful value — it has no type or value.</div> + + <div class="note"><strong>Note</strong>: This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the <code>checkGuess() { ... }</code> block). As you'll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the <code>checkGuess()</code> function was run by line 86.</div> + </li> + <li>Have a look at line 78, and you'll see the following code: + <pre class="brush: js">lowOrHi.textContent = 'Last guess was too high!';</pre> + </li> + <li>This line is trying to set the <code>textContent</code> property of the <code>lowOrHi</code> variable to a text string, but it's not working because <code>lowOrHi</code> does not contain what it's supposed to. Let's see why this is — try searching for other instances of <code>lowOrHi</code> in the code. The earliest instance you'll find in the JavaScript is on line 48: + <pre class="brush: js">var lowOrHi = document.querySelector('lowOrHi');</pre> + </li> + <li>At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's check whether the value is <code>null</code> after this line has been run. Add the following code on line 49: + <pre class="brush: js">console.log(lowOrHi);</pre> + + <div class="note"> + <p><strong>Note</strong>: <code><a href="/en-US/docs/Web/API/Console/log">console.log()</a></code> is a really useful debugging function that prints a value to the console. So it will print the value of <code>lowOrHi</code> to the console as soon as we have tried to set it in line 48.</p> + </div> + </li> + <li>Save and refesh, and you should now see the <code>console.log()</code> result in your console. <img alt="" src="https://mdn.mozillademos.org/files/13494/console-log-output.png" style="display: block; margin: 0 auto;"> Sure enough, <code>lowOrHi</code>'s value is <code>null</code> at this point, so there is definitely a problem with line 48.</li> + <li>Let's think about what the problem could be. Line 48 is using a <code><a href="/en-US/docs/Web/API/Document/querySelector">document.querySelector()</a></code> method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question: + <pre class="brush: js"><p class="lowOrHi"></p></pre> + </li> + <li>So we need a class selector here, which begins with a dot (.), but the selector being passed into the <code>querySelector()</code> method in line 48 has no dot. This could be the problem! Try changing <code>lowOrHi</code> to <code>.lowOrHi</code> in line 48.</li> + <li>Try saving and refreshing again, and your <code>console.log()</code> statement should return the <code><p></code> element we want. Phew! Another error fixed! You can delete your <code>console.log()</code> line now, or keep it to reference later on — your choice.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_type">TypeError: "x" is (not) "y"</a> reference page for more details about this error.</p> +</div> + +<h3 id="Syntax_errors_round_three">Syntax errors round three</h3> + +<ol> + <li>Now if you try playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of lives.</li> + <li>At that point, the game fails again, and the same error is spat out that we got at the beginning — "TypeError: resetButton.addeventListener is not a function"! However, this time it's listed as coming from line 94.</li> + <li>Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change <code>addeventListener</code> to <code>.addEventListener</code>. Do this now.</li> +</ol> + +<h2 id="A_logic_error">A logic error</h2> + +<p>At this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the "random" number you've got to guess is always 1. Definitely not quite how we want the game to play out!</p> + +<p>There's definitely a problem in the game logic somewhere — the game is not returning an error; it just isn't playing right.</p> + +<ol> + <li>Search for the <code>randomNumber</code> variable, and the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the game should be around line number 44: + + <pre class="brush: js">var randomNumber = Math.floor(Math.random()) + 1;</pre> + And the one that generates the random number before each subsequent game is around line 113:</li> + <li> + <pre class="brush: js">randomNumber = Math.floor(Math.random()) + 1;</pre> + </li> + <li>To check whether these lines are indeed the problem, let's turn to our friend <code>console.log()</code> again — insert the following line directly below each of the above two lines: + <pre class="brush: js">console.log(randomNumber);</pre> + </li> + <li>Save and refresh, then play a few games — you'll see that <code>randomNumber</code> is equal to 1 at each point where it is logged to the console.</li> +</ol> + +<h3 id="Working_through_the_logic">Working through the logic</h3> + +<p>To fix this, let's consider how this line is working. First, we invoke <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a></code>, which generates a random decimal number between 0 and 1, e.g. 0.5675493843.</p> + +<pre class="brush: js">Math.random()</pre> + +<p>Next, we pass the result of invoking <code>Math.random()</code> through <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor">Math.floor()</a></code>, which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:</p> + +<pre>Math.floor(Math.random()) + 1</pre> + +<p>Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:</p> + +<pre class="brush: js">Math.floor(Math.random()*100);</pre> + +<p>Hence us wanting to add 1, to give us a random number between 1 and 100:</p> + +<pre class="brush: js">Math.floor(Math.random()*100) + 1;</pre> + +<p>Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!</p> + +<h2 id="Other_common_errors">Other common errors</h2> + +<p>There are other common errors you'll come across in your code. This section highlights most of them.</p> + +<h3 id="SyntaxError_missing_before_statement">SyntaxError: missing ; before statement</h3> + +<p>This error generally means that you have missed a semi colon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the <code>checkGuess()</code> function:</p> + +<pre class="brush: js">var userGuess = Number(guessField.value);</pre> + +<p>to</p> + +<pre class="brush: js">var userGuess === Number(guessField.value);</pre> + +<p>It throws this error because it thinks you are trying to do something different. You should make sure that you don't mix up the assignment operator (<code>=</code>) — which sets a variable to be equal to a value — with the strict equality operator (<code>===</code>), which tests whether one value is equal to another, and returns a <code>true</code>/<code>false</code> result.</p> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement">SyntaxError: missing ; before statement</a> reference page for more details about this error.</p> +</div> + +<h3 id="The_program_always_says_you've_won_regardless_of_the_guess_you_enter">The program always says you've won, regardless of the guess you enter</h3> + +<p>This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside <code>checkGuess()</code>:</p> + +<pre class="brush: js">if (userGuess === randomNumber) {</pre> + +<p>to</p> + +<pre class="brush: js">if (userGuess = randomNumber) {</pre> + +<p>the test would always return <code>true</code>, causing the program to report that the game has been won. Be careful!</p> + +<h3 id="SyntaxError_missing_)_after_argument_list">SyntaxError: missing ) after argument list</h3> + +<p>This one is pretty simple — it generally means that you've missed the closing parenthesis off the end of a function/method call.</p> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list">SyntaxError: missing ) after argument list</a> reference page for more details about this error.</p> +</div> + +<h3 id="SyntaxError_missing_after_property_id">SyntaxError: missing : after property id</h3> + +<p>This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing</p> + +<pre class="brush: js">function checkGuess() {</pre> + +<p>to</p> + +<pre class="brush: js">function checkGuess( {</pre> + +<p>This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!</p> + +<h3 id="SyntaxError_missing_after_function_body">SyntaxError: missing } after function body</h3> + +<p>This is easy — it generally means that you've missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the <code>checkGuess()</code> function.</p> + +<h3 id="SyntaxError_expected_expression_got_'string'_or_SyntaxError_unterminated_string_literal">SyntaxError: expected expression, got '<em>string</em>' or SyntaxError: unterminated string literal</h3> + +<p>These errors generally mean that you've missed off a string value's opening or closing quote mark. In the first error above, <em>string</em> would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.</p> + +<p>For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what's wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!</p> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_token">SyntaxError: Unexpected token</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal">SyntaxError: unterminated string literal</a> reference pages for more details about these errors.</p> +</div> + +<h2 id="Summary">Summary</h2> + +<p>So there we have it, the basics of figuring out errors in simple JavaScript programs. It won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right earlier on in your learning journey.</p> + +<h2 id="See_also">See also</h2> + +<div> +<ul> + <li>There are many other types of errors that aren't listed here; we are compiling a reference that explains what they mean in detail — see the <a href="/en-US/docs/Web/JavaScript/Reference/Errors">JavaScript error reference</a>.</li> + <li>If you come across any errors in your code that you aren't sure how to fix after reading this article, you can get help! Ask on the <a class="external external-icon" href="https://discourse.mozilla-community.org/t/learning-web-development-marking-guides-and-questions/16294">Learning Area Discourse thread</a>, or in the <a href="irc://irc.mozilla.org/mdn">#mdn</a> IRC channel on <a class="external external-icon" href="https://wiki.mozilla.org/IRC">Mozilla IRC</a>. Tell us what your error is, and we'll try to help you. A listing of your code would be useful as well.</li> +</ul> +</div> + +<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> diff --git a/files/it/learn/javascript/first_steps/index.html b/files/it/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..220f1f25c1 --- /dev/null +++ b/files/it/learn/javascript/first_steps/index.html @@ -0,0 +1,68 @@ +--- +title: JavaScript First Steps +slug: Learn/JavaScript/First_steps +tags: + - Arrays + - Article + - Assessment + - Beginner + - CodingScripting + - Guide + - JavaScript + - Landing + - Module + - NeedsTranslation + - Numbers + - Operators + - TopicStub + - Variables + - 'l10n:priority' + - maths + - strings +translation_of: Learn/JavaScript/First_steps +--- +<p class="summary">{{LearnSidebar}}Nel nostro primo modulo JavaScript, per prima cosa, rispondiamo ad alcune domande fondamentali come "cosa è JavaScript?", "a che cosa assomiglia?", e "cosa può fare?", prima di guidarti nella tua prima esperienza pratica di scrittura JavaScript. Dopodiché, discuteremo dettagliatamente, alcuni elementi chiave, come variabili, stringhe, numeri ed array.</p> + +<h2 id="Prerequisiti">Prerequisiti</h2> + +<p>Prima di iniziare questo modulo, non hai bisogno di alcuna precedente conoscenza di JavaScript, ma dovresti avere familiarità con HTML e CSS. Si consiglia di utilizzare i seguenti moduli prima di iniziare su JavaScript:</p> + +<ul> + <li><a href="/it/docs/Learn/Getting_started_with_the_web">Iniziare con il Web</a> (che include <a href="/it/docs/Getting_started_with_the_web/JavaScript_basics">un'introduzione Javascript realmente di base</a>)</li> + <li><a href="/it/docs/Learn/HTML/Introduction_to_HTML">Introduzione ad HTML</a>.</li> + <li><a href="/it/docs/Learn/CSS/Introduction_to_CSS">Introduzione a CSS</a>.</li> +</ul> + +<div class="note"> +<p><strong>Nota:</strong> Se stai lavorando su un computer/tablet/altro dispositivo dove non sei in grado di creare i tuoi files, potresti provare (la maggior parte) gli esempi di codice in un programma di codifica online come <a href="http://jsbin.com/">JSBin</a> o <a href="https://thimble.mozilla.org/">Thimble</a>.</p> +</div> + +<h2 id="Guide">Guide</h2> + +<dl> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/What_is_JavaScript">Cosa è JavaScript?</a></dt> + <dd>Benvenuto nel corso JavaScript per principianti di MDN! In questo primo articolo vedremo JavaScript da un livello alto, rispondendo a domande come "cosa è JavaScript?" e "cosa sta facendo?", e assicurandoci che tu sia a tuo agio con lo scopo di JavaScript.</dd> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/A_first_splash">Un primo tuffo in JavaScript</a></dt> + <dd>Ora che hai imparato qualcosa sulla teoria di JavaScript, e cosa puoi fare con esso, stiamo per fornirti un corso accelerato sulle caratteristiche di base di JavaScript attraverso un tutorial totalmente pratico. Qui costruirai un semplice gioco "Indovina il numero", passo dopo passo.</dd> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/What_went_wrong">Cosa è andato storto? Risoluzione dei problemi di JavaScript</a></dt> + <dd>Quando hai costruito il gioco "Indovina il numero" nel precedente articolo, potresti aver trovato che non funzionava. Nessuna paura - questo articolo mira a salvarti dallo strapparti i capelli su questi problemi fornendoti alcuni semplici consigli sul come trovare e correggere gli errori nei programmi JavaScript.</dd> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/Variables">Memorizzare le informazioni ci cui hai bisogno - le Variabili</a></dt> + <dd>Dopo aver letto l'ultima coppia di articoli dovresti sapere cos'è JavaScript, cosa può fare per te, come usarlo con altre tecnologie web, e come le sue principali caratteristiche appaiono da un livello alto. In questo articolo andremo giù fino alle basi reali, guardando come lavorare con i blocchi di costruzione più semplici di JavaScript - Variabili.</dd> + <dt>Matemeatica di base in JavaScript - numeri e operatori</dt> + <dd>A questo punto del corso discuteremo matematica in JavaScript — come possiamo combinare operatori ed altre funzioni per manipolare con successo i numeri per fare i nostri bidding.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></dt> + <dd>Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></dt> + <dd>Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></dt> + <dd>In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.</dd> +</dl> + +<h2 id="Assessments">Assessments</h2> + +<p>The following assessment will test your understanding of the JavaScript basics covered in the guides above.</p> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Silly story generator</a></dt> + <dd>In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!</dd> +</dl> diff --git a/files/it/learn/javascript/first_steps/variabili/index.html b/files/it/learn/javascript/first_steps/variabili/index.html new file mode 100644 index 0000000000..38da82e607 --- /dev/null +++ b/files/it/learn/javascript/first_steps/variabili/index.html @@ -0,0 +1,337 @@ +--- +title: Memorizzazione delle informazioni necessarie - Variabili +slug: Learn/JavaScript/First_steps/Variabili +translation_of: Learn/JavaScript/First_steps/Variables +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">Dopo aver letto gli ultimi due articoli, ora dovresti sapere cos'è JavaScript, cosa può fare per te, come lo usi insieme ad altre tecnologie web e quali sono le sue caratteristiche principali da un livello elevato. In questo articolo, passeremo alle basi reali, esaminando come lavorare con i blocchi di base di JavaScript - Variabili.</p> + +<table class="learn-box"> + <tbody> + <tr> + <th scope="row">Prerequisiti:</th> + <td>Nozioni di base di informatica, comprensione di base di HTML e CSS, comprensione di cosa sia JavaScript</td> + </tr> + <tr> + <th scope="row">Obiettivo:</th> + <td>Acquisire familiarità con le basi delle variabili JavaScript.</td> + </tr> + </tbody> +</table> + +<h2 id="Strumenti_di_cui_hai_bisogno">Strumenti di cui hai bisogno</h2> + +<p>In questo articolo ti verrà chiesto di digitare righe di codice per testare la tua comprensione del contenuto. Se si utilizza un browser desktop, il posto migliore per digitare il codice di esempio è la console JavaScript del browser (vedere <a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">Quali sono gli strumenti di sviluppo</a> del browser per ulteriori informazioni su come accedere a questo strumento).</p> + +<h2 id="Cosa_è_una_variabile">Cosa è una variabile?</h2> + +<p>Una variabile è un contenitore per un valore, come un numero che potremmo usare in una somma o una stringa che potremmo usare come parte di una frase. Ma una cosa speciale delle variabili è che i loro valori possono cambiare. Diamo un'occhiata a un semplice esempio:</p> + +<pre class="brush: html notranslate"><button>Press me</button></pre> + +<pre class="brush: js notranslate">const button = document.querySelector('button'); + +button.onclick = function() { + let name = prompt('What is your name?'); + alert('Hello ' + name + ', nice to see you!'); +}</pre> + +<p>{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}</p> + +<p>In questo esempio, premendo il bottone viene eseguito un paio di righe di codice. La prima riga apre una finestra sullo schermo che chiede al lettore di inserire il proprio nome, quindi memorizza il valore in una variabile. La seconda riga mostra un messaggio di benvenuto che include il loro nome, preso dal valore della variabile.</p> + +<p>Per capire perché questo è così utile, pensiamo a come scrivere questo esempio senza usare una variabile. Finirebbe per assomigliare a questo:</p> + +<pre class="example-bad notranslate">let name = prompt('What is your name?'); + +if (name === 'Adam') { + alert('Hello Adam, nice to see you!'); +} else if (name === 'Alan') { + alert('Hello Alan, nice to see you!'); +} else if (name === 'Bella') { + alert('Hello Bella, nice to see you!'); +} else if (name === 'Bianca') { + alert('Hello Bianca, nice to see you!'); +} else if (name === 'Chris') { + alert('Hello Chris, nice to see you!'); +} + +// ... and so on ...</pre> + +<p>Potresti non comprendere appieno la sintassi che stiamo usando (ancora!), ma dovresti essere in grado di farti un'idea - se non avessimo variabili disponibili, dovremmo implementare un blocco di codice gigante che controlla quale sia il nome inserito e quindi visualizzare il messaggio appropriato per quel nome. Questo è ovviamente molto inefficiente (il codice è molto più grande, anche solo per cinque scelte), e semplicemente non funzionerebbe - non è possibile memorizzare tutte le possibili scelte.</p> + +<p>Le variabili hanno senso e, man mano che impari di più su JavaScript, inizieranno a diventare una seconda natura.</p> + +<p>Un'altra cosa speciale delle variabili è che possono contenere qualsiasi cosa, non solo stringhe e numeri. Le variabili possono anche contenere dati complessi e persino intere funzioni per fare cose sorprendenti. Imparerai di più su questo mentre procedi.</p> + +<div class="note"> +<p><strong>Nota</strong>:Diciamo che le variabili contengono valori. Questa è una distinzione importante da fare. Le variabili non sono i valori stessi; sono contenitori per valori. Puoi pensare che siano come piccole scatole di cartone in cui puoi riporre le cose.</p> +</div> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13506/boxes.png" style="display: block; height: 436px; margin: 0px auto; width: 1052px;"></p> + +<h2 id="Dichiarare_una_variabile">Dichiarare una variabile</h2> + +<p>Per usare una variabile, devi prima crearla - più precisamente, dobbiamo dichiarare la variabile. Per fare ciò, utilizziamo la parola chiave var o let seguita dal nome che vuoi chiamare la tua variabile:</p> + +<pre class="brush: js notranslate">let myName; +let myAge;</pre> + +<p>Qui stiamo creando due variabili chiamate myName e myAge. Prova a digitare queste righe nella console del tuo browser web. Successivamente, prova a creare una (o due) variabili chiamandole a tuo piacimento.</p> + +<div class="note"> +<p><strong>Nota</strong>: In JavaScript, tutte le istruzioni del codice dovrebbero terminare con un punto e virgola (;) - il codice potrebbe funzionare correttamente per singole righe, ma probabilmente non funzionerà quando si scrivono più righe di codice insieme. Cerca di prendere l'abitudine di includerlo.</p> +</div> + +<p>Puoi verificare se questi valori ora esistono nell'ambiente di esecuzione digitando solo il nome della variabile, ad es.</p> + +<pre class="brush: js notranslate">myName; +myAge;</pre> + +<p>Al momento non hanno valore; sono contenitori vuoti. Quando si immettono i nomi delle variabili, è necessario ottenere un valore <kbd>undefined</kbd>. Se non esistono, verrà visualizzato un messaggio di errore: "try typing in</p> + +<pre class="brush: js notranslate">scoobyDoo;</pre> + +<div class="note"> +<p><strong>Nota</strong>: Non confondere una variabile esistente ma che non ha alcun valore definito con una variabile che non esiste affatto: sono cose molto diverse. Nell'analogia della scatola che hai visto sopra, non esistere significherebbe che non esiste una scatola (variabile) in cui inserire un valore. Nessun valore definito significherebbe che c'è una scatola, ma non ha alcun valore al suo interno.</p> +</div> + +<h2 id="Inizializzare_una_Variabile">Inizializzare una Variabile</h2> + +<p>Una volta che hai dichiarato una variabiale, puoi inizializzarla con un valore. Puoi farlo digitando il nome della variabile, seguito dal segno di uguale (=), seguito poi dal valore che vuoi dargli. Per esempio: </p> + +<pre class="brush: js notranslate">myName = 'Chris'; +myAge = 37;</pre> + +<p>Prova a tornare alla console ora e digita queste linee. Dovresti vedere il valore che hai assegnato alla variabile restituita nella console per confermarla, in ogni caso. Ancora una volta, puoi restituire i valori delle variabili semplicemente digitandone il nome nella console. Riprova:</p> + +<pre class="brush: js notranslate">myName; +myAge;</pre> + +<p>Puoi dichiarare e inizializzare una variabile nello stesso tempo, come questo: </p> + +<pre class="brush: js notranslate">let myDog = 'Rover';</pre> + +<p>Questo è probabilmente ciò che farai la maggior parte del tempo, essendo il metodo più veloce rispetto alle due azioni separate. </p> + +<h2 id="Differenza_tra_var_e_let">Differenza tra var e let</h2> + +<p>A questo punto potresti pensare "perchè abbiamo bisogno di due keywords (parole chiavi) per definire le variabili?? Perchè avere <code>var</code> e <code>let</code>?".</p> + +<p>Le ragioni sono in qualche modo storiche. Ai tempi della creazione di JavaScript, c'era solo <code>var</code>. Questa funziona fondamentalmente in molti casi, ma ha alcuni problemi nel modo in cui funziona — il suo design può qualche volta essere confuso o decisamente fastidioso. Così, <code>let</code> è stata creata nella moderna versione di JavaScript, una nuova keyword (parola chiave) per creare variabili che funzionano differentemente da <code>var</code>, risolvendo i suoi problemi nel processo.</p> + +<p>Di seguito sono spiegate alcune semplici differenze. Non le affronteremo ora tutte, ma inizierai a scoprirle mentre impari più su JavaScript. (se vuoi davvero leggere su di loro ora, non esitare a controllare la nostra pagina di riferimento <a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a>).</p> + +<p>Per iniziare, se scrivi un multilinea JavaScript che dichiara e inizializza una variabile, puoi effettivamente dichiarare una variabile con <code>var</code> dopo averla inizializzata funzionerà comunque. Per esempio:</p> + +<pre class="brush: js notranslate">myName = 'Chris'; + +function logName() { + console.log(myName); +} + +logName(); + +var myName;</pre> + +<div class="note"> +<p><strong>Nota: </strong> Questo non funziona quando digiti linee individuali in una JavaScript console, ma solo quando viene eseguita in linee multiple in un documento web. </p> +</div> + +<p>Questo lfunziona a causa di <strong>hoisting</strong> — leggi <a href="/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting">var hoisting</a> per maggiori dettagli sull'argomento. </p> + +<p>Hoisting non funziona con <code>let</code>. Se cambiamo <code>var</code> a <code>let</code> nell'esempio precedente, da un errore. Questa è una buona cosa — dichiarare una variabile dopo che averla inizializzata si traduce in un codice confuso e difficile da capire.</p> + +<p>In secondo luogo, quando usi <code>var</code>, puoi dichiarare la stessa variabile tutte le volte che vuoi, ma con <code>let</code> non puoi. Quanto segue funzionerebbe: </p> + +<pre class="brush: js notranslate">var myName = 'Chris'; +var myName = 'Bob';</pre> + +<p>Ma il seguente darebbe un errore sulla seconda linea: </p> + +<pre class="brush: js notranslate">let myName = 'Chris'; +let myName = 'Bob';</pre> + +<p>Dovresti invece fare questo: </p> + +<pre class="brush: js notranslate">let myName = 'Chris'; +myName = 'Bob';</pre> + +<p>Ancora una volta, questa è un scelta linquistica più corretta. Non c'è motivo di ridichiarare le variabili: rende le cose più confuse.</p> + +<p>Per queste ragioni e altre, noi raccomandiamo di usare <code>let</code> il più possibile nel tuo codice, piuttosto che <code>var</code>. Non ci sono motivi per usare <code>var</code>, a meno che non sia necessario supportare vecchie versioni di Internet Explorer proprio con il tuo codice. ( <code>let</code> non è supportato fino fino alla versione 11, il moderno Windows Edge browser supporta bene <code>let</code>).</p> + +<div class="note"> +<p><strong>Nota: </strong> Attualmente stiamo aggiornando il corso per usare più <code>let</code> piuttosto che <code>var</code>. Abbi pazienza con noi!</p> +</div> + +<h2 id="Aggiornare_una_variabile">Aggiornare una variabile</h2> + +<p>Una volta che una variabile è stata inizializzata con un valore, puoi cambiarlo (o aggiornarlo) dandogli semplicemente un valore differente. Prova a inserire le seguenti linee nella tua console: </p> + +<pre class="brush: js notranslate">myName = 'Bob'; +myAge = 40;</pre> + +<h3 id="Regole_di_denominazione_delle_variabili">Regole di denominazione delle variabili</h3> + +<p>Puoi chiamare una variabile praticamente come preferisci, ma ci sono delle limitazioni. Generalmente, dovresti limitarti ad usare i caratteri latini (0-9, a-z, A-Z) e l'underscore ( _ ).</p> + +<ul> + <li>Non dovresti usare altri caratteri perchè possono causare errori o essere difficili da capire per un pubblico internazionale. </li> + <li>Non usare l'underscores all'inizio di un nome di una variabile — questo è usato in alcuni costrutti JavaScript per dire cose specifiche, quindi può generare confusione. </li> + <li>Non usare numeri all'inizio di una variabile. Questo non è permesso e causa un errore. </li> + <li>Una convezione sicura alla quale attenersi si chiama <a href="https://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms">"notazione a cammello"</a>, dove per unire più parole, si usa il minuscolo per la prima parola e la lettera maiuscola per le seguenti parole. Abbiamo usato questo per i nomi delle variabili in questo articolo. (es: myName)</li> + <li>Creare i nomi delle variabili intuitivi, in modo che descrivano i dati che contengono. Non usare singole lettere / numeri, o lunghe frasi.</li> + <li>Le variabili sono case sensitive — così <code>myage</code> è differente da <code>myAge</code>.</li> + <li>Ultimo punto: devi evitare di usare parole riservate a JavaScript come nomi delle variabili — con questo intendiamo le parole che compongono la sintassi effettiva di JavaScript! Così, non puoi usare parole come <code>var</code>, <code>function</code>, <code>let</code>, e <code>for</code> come nomi di variabili. I browsers li riconoscono come elementi differenti di codice, e così danno errore. </li> +</ul> + +<div class="note"> +<p><strong>Nota</strong>: Puoi trovare un elenco abbastanza completo di parole riservate da evitare a <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">Lexical grammar — keywords</a>.</p> +</div> + +<p>Esempi di nomi corretti: </p> + +<pre class="example-good notranslate">age +myAge +init +initialColor +finalOutputValue +audio1 +audio2</pre> + +<p>Esempi di nomi errati: </p> + +<pre class="example-bad notranslate">1 +a +_12 +myage +MYAGE +var +Document +skjfndskjfnbdskjfb +thisisareallylongstupidvariablenameman</pre> + +<p>Esempi di nomi soggetti a errori: </p> + +<pre class="example-invalid notranslate">var +Document +</pre> + +<p>Prova a creare qualche altra variabile ora, tenendo presente le indicazioni sopra riportate. </p> + +<h2 id="Tipi_di_Variabili">Tipi di Variabili</h2> + +<p>Esistono diversi tipi di dati che possiamo archiviare in variabili. In questa sezione li descriveremo in breve, quindi in articoli futuri, imparerai su di loro in modo più dettagliato.</p> + +<p>Finora abbiamo esaminato i primi due, ma che ne sono altri. </p> + +<h3 id="Numeri">Numeri</h3> + +<p>Puoi memorizzare numeri nelle variabili, numeri interi come 30 o numeri decimali come 2,456 (chiamati anche numeri mobili o in virgola mobile). Non è necessario dichiarare i tipi di variabili in JavaScript, a differenza di altri linguaggi di programmazione. Quando dai a una variabile un valore numerico, non si usa le virgolette:</p> + +<pre class="brush: js notranslate">let myAge = 17;</pre> + +<h3 id="Stringhe">Stringhe</h3> + +<p>Le stringhe sono pezzi di testo. Quando dai a una variabile un valore di una stringa, hai bisogno di metterla in singole o doppie virgolette; altrimenti, JavaScript cerca di interpretarlo come un altro nome della variabile. </p> + +<pre class="brush: js notranslate">let dolphinGoodbye = 'So long and thanks for all the fish';</pre> + +<h3 id="Booleani">Booleani</h3> + +<p>I booleani sono dei valori vero/falso — possono avere due valori <code>true</code> o <code>false</code>. Questi sono generalmente usati per testare delle condizioni, dopo di che il codice viene eseguito come appropriato . Ad esempio, un semplice caso sarebbe:</p> + +<pre class="brush: js notranslate">let iAmAlive = true;</pre> + +<p>Considerando che in realtà sarebbe usato più così:</p> + +<pre class="brush: js notranslate">let test = 6 < 3;</pre> + +<p>Questo sta usando l'operatore "minore di" (<code><</code>) per verificare se 6 è minore di 3. Come ci si potrebbe aspettare, restituisce <code>false</code>, perché 6 non è inferiore a 3! Imparerai molto di più su questi operatori più avanti nel corso.</p> + +<h3 id="Arrays">Arrays</h3> + +<p>Un array è un singolo oggetto che contiene valori multipli racchiusi in parentesi quadre e separate da virgole. Prova a inserire le seguenti linee nella tua console:</p> + +<pre class="brush: js notranslate">let myNameArray = ['Chris', 'Bob', 'Jim']; +let myNumberArray = [10, 15, 40];</pre> + +<p>Una volta che gli arrays sono definiti, è possibile accedere a ciascun valore in base alla posizione all'interno dell'array. Prova queste linee:</p> + +<pre class="brush: js notranslate">myNameArray[0]; // should return 'Chris' +myNumberArray[2]; // should return 40</pre> + +<p>Le parentesi quadre specificano un valore di indice corrispondente alla posizione del valore che si desidera restituire. Potresti aver notato che gli array in JavaScript sono indicizzatI a zero: il primo elemento si trova all'indice 0.</p> + +<p>Puoi imparare molto sugli arrays in <a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">un futuro articolo</a>.</p> + +<h3 id="Oggetti">Oggetti</h3> + +<p>In programmazione, un oggetto è una struttura di codice che modella un oggetto reale. Puoi avere un oggetto semplice che rappresenta una box e contiene informazioni sulla sua larghezza, lunghezza e altezza, oppure potresti avere un oggetto che rappresenta una persona e contenere dati sul suo nome, altezza, peso, quale lingua parla, come salutarli<br> + e altro ancora.</p> + +<p>Prova a inserire il seguente codice nella tua console:</p> + +<pre class="brush: js notranslate">let dog = { name : 'Spot', breed : 'Dalmatian' };</pre> + +<p>Per recuperare le informazioni archiviate nell'oggetto, è possibile utilizzare la seguente sintassi:</p> + +<pre class="brush: js notranslate">dog.name</pre> + +<p>Per ora non esamineremo più gli oggetti: puoi saperne di più su quelli in un <a href="/en-US/docs/Learn/JavaScript/Objects"> modulo futuro.</a></p> + +<h2 id="Tipizzazione_dinamica">Tipizzazione dinamica</h2> + +<p>JavaScript è un "linguaggio a tipizzazione dinamica", questo significa che, a differenza di altri linguaggi, non è necessario specificare quale tipo di dati conterrà una variabile (numeri, stringhe, array, ecc.).</p> + +<p>Ad esempio, se dichiari una variabile e le assegni un valore racchiuso tra virgolette, il browser considera la variabile come una stringa:</p> + +<pre class="brush: js notranslate">let myString = 'Hello';</pre> + +<p>Anche se il valore contiene numeri, è comunque una stringa, quindi fai attenzione:</p> + +<pre class="brush: js notranslate">let myNumber = '500'; // oops, questa è ancora una stringa +typeof myNumber; +myNumber = 500; // molto meglio - adesso questo è un numero +typeof myNumber;</pre> + +<p>Prova a inserire le quattro righe sopra nella console una per una e guarda quali sono i risultati. Noterai che stiamo usando un speciale operatore chiamato <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code>- questo restituisce il tipo di dati della variabile che scrivi dopo. La prima volta che viene chiamato, dovrebbe restituire <code>string</code>, poiché a quel punto la variabile <code>myNumber</code> contiene una stringa, <code>'500'</code>.<br> + Dai un'occhiata e vedi cosa restituisce la seconda volta che lo chiami.</p> + +<h2 id="Costanti_in_JavaScript">Costanti in JavaScript</h2> + +<p>Molti linguaggi di programmazione hanno il concetto di <em>costante</em> - un valore che una volta dichiarato non può mai essere modificato. Ci sono molte ragioni per cui vorresti farlo, dalla sicurezza (se uno script di terze parti ha cambiato tali valori potrebbe causare problemi) al debug e alla comprensione del codice (è più difficile cambiare accidentalmente valori che non dovrebbero essere cambiati e fare confusione).</p> + +<p>All'inizio di JavaScript, le costanti non esistevano. Nel moderno JavaScript, abbiamo la parola chiave <code>const</code>, che ci consente di memorizzare valori che non possono mai essere modificati:</p> + +<pre class="brush: js notranslate">const daysInWeek = 7<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number">; +const hoursInDay = 24;</span></span></span></span></pre> + +<p><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number"><code>const</code> lavora esattamente come <code>let</code>, eccetto che non puoi dare a<code>const</code> un nuovo valore. Nell'esempio seguente, la seconda linea genera un errore:</span></span></span></span></p> + +<pre class="brush: js notranslate">const daysInWeek = 7<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number">; +daysInWeek = 8;</span></span></span></span></pre> + +<h2 id="Sommario">Sommario </h2> + +<p>Ormai dovresti conoscere una quantità ragionevole di variabili JavaScript e come crearle. Nel prossimo articolo, ci concentreremo sui numeri in modo più dettagliato, esaminando come eseguire la matematica di base in JavaScript.</p> + +<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">The first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> diff --git a/files/it/learn/javascript/index.html b/files/it/learn/javascript/index.html new file mode 100644 index 0000000000..faa1dc8f1a --- /dev/null +++ b/files/it/learn/javascript/index.html @@ -0,0 +1,63 @@ +--- +title: JavaScript +slug: Learn/JavaScript +tags: + - JavaScript + - Principiante + - ScrtturaCodice +translation_of: Learn/JavaScript +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">{{Glossary("JavaScript")}} è un linguaggio di programmazione che consente la creazione di oggetti complessi in pagine web. Ogni volta che una pagina web fa più che visualizzare semplici informazioni statiche — visualizzando contenuti aggiornati su base temporale, mappe interattive, o animazioni grafiche 2D/3D, o scrolling video jukeboxes, ecc... ecc... — si può presumere che JavaScript sia coinvolto.</p> + +<h2 id="Percorso_di_apprendimento">Percorso di apprendimento</h2> + +<p>JavaScript è sicuramente più difficile da imparare rispetto alle tecnologie ad esso correlate, come <a href="/en-US/docs/Learn/HTML">HTML</a> and <a href="/en-US/docs/Learn/CSS">CSS</a>. Prima di tentare di imparare JavaScript, <span id="result_box" lang="it"><span>si consiglia vivamente di familiarizzare innanzitutto con almeno queste due tecnologie, e forse anche con altre. Inizia a lavorare sui seguenti moduli:</span></span></p> + +<ul> + <li><a href="/it/docs/Learn/Getting_started_with_the_web">Primi passi nel Web</a></li> + <li><a href="/it/docs/Web/Guide/HTML/Introduction">Introduzione ad HTML</a></li> + <li><a href="/it/docs/Learn/CSS/Introduction_to_CSS">Introduzione a CSS</a></li> +</ul> + +<p>Una pregressa esperienza con altri linguaggi di programmazione può essere senz'altro utile.</p> + +<p>Dopo aver familiarizzato con i concetti base di JavaScript, dovresti essere in grado di imparare argomenti più complessi, per esempio:</p> + +<ul> + <li>JavaScript in profondità, come insegnato nella nostra <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript guide</a></li> + <li><a href="/en-US/docs/Web/API">HTML5 APIs</a></li> +</ul> + +<h2 id="Moduli">Moduli</h2> + +<p>Questo tema contiene i seguenti moduli, in un<span class="short_text" id="result_box" lang="it"><span> ordine suggerito per lavorarci sopra.</span></span></p> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps">Primi passi JavaScript</a></dt> + <dd>Nel nostro primo modulo JavaScript, rispondiamo dapprima a domande fondamentali come "cos'è JavaScript?", "come è fatto?" e "cosa può fare?", prima di proseguire guidandoti attraverso le prime esperienze di scrittura di codice JavaScript. In seguito, <span id="result_box" lang="it"><span>presentiamo in dettaglio </span></span><span lang="it"><span>alcune caratteristiche chiave di JavaScript, come variabili, stringhe, numeri e matrici (arrays).</span></span></dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks">Blocchi costruttivi JavaScript</a></dt> + <dd>In questo modulo continuiamo la nostra descrizione di tutte<span id="result_box" lang="it"><span> le principali caratteristiche chiave di JavaScript, rivolgendo la nostra attenzione ai tipi di blocco di codice comunemente incontrati come dichiarazioni condizionali, cicli, funzioni ed eventi. Hai già visto questi elementi nel corso, ma solo di passaggio - qui discuteremo tutto in modo esplicito.</span></span></dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects">Introduzione a oggetti JavaScript</a></dt> + <dd>In JavaScript, <span id="result_box" lang="it"><span>la maggior parte degli elementi sono oggetti, dalle funzionalità di base di JavaScript come stringhe e matrici alle API del browser create sulla base di JavaScript.</span> <span>È anche possibile creare dei propri oggetti per incapsulare funzioni e variabili correlate in pacchetti efficienti (packages)</span></span><span lang="it"><span>. </span></span><span id="result_box" lang="it"><span>La natura orientata agli oggetti di JavaScript è importante che sia compresa se vuoi andare oltre con la tua conoscenza del linguaggio e scrivere codice più efficiente, quindi abbiamo creato questo modulo per aiutarti.</span> <span>Qui insegniamo la teoria degli oggetti e la sua sintassi in dettaglio, vediamo come puoi creare i tuoi oggetti e spieghiamo cosa sono i dati JSON e come lavorarci.</span></span></dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Web APIs lato Client</a></dt> + <dd><span id="result_box" lang="it"><span>Quando si scrive JavaScript sul lato client per siti Web o applicazioni, non si andrà molto lontano prima di iniziare a utilizzare le API </span></span>— <span lang="it"><span>interfacce per la manipolazione di diversi aspetti del browser e del sistema operativo su cui è in esecuzione il sito, o anche dati da altri siti Web</span> <span>o servizi.</span> <span>In questo modulo esploreremo quali sono le API e come utilizzare alcune delle API più comuni che incontrerai spesso nel tuo lavoro di sviluppatore.</span></span></dd> +</dl> + +<h2 id="Risolvere_i_problemi_tipici_di_JavaScript">Risolvere i problemi tipici di JavaScript</h2> + +<p><a href="/en-US/docs/Learn/JavaScript/Howto">Usa JavaScript per risolvere i problemi tipici</a> <span id="result_box" lang="it"><span>fornisce collegamenti a sezioni di contenuto che spiegano come usare JavaScript per risolvere problemi molto comuni durante la creazione di una pagina web.</span></span></p> + +<h2 id="Vedi_anche">Vedi anche</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript">JavaScript su MDN</a></dt> + <dd><span id="result_box" lang="it"><span>Il punto di ingresso principale per la documentazione base di JavaScript su MDN</span></span> —<span lang="it"><span> qui è possibile trovare documenti di riferimento completi su tutti gli aspetti del linguaggio JavaScript e alcuni tutorial avanzati rivolti a esperti JavaScript.</span></span></dd> + <dt><a href="https://learnjavascript.online/">Imparare JavaScript</a> </dt> + <dd>Un eccellente risorsa (in inglese) per aspiranti sviluppatori web — Imparare JavaScript in un ambiente interattivo, con lezioni brevi e test interattivi, guidati da valutazioni automatiche. le prime 40 lezioni sono gratuite, e il corso completo è disponibile con un piccolo pagamento una tantum. </dd> + <dt><a href="https://exlskills.com/learn-en/courses/javascript-fundamentals-basics_javascript">Basi di JavaScript su EXLskills</a></dt> + <dd>Impara JavaScript con il corso open-source gratuito di EXLskills che presenta tutto ciò che ti occorre per iniziare a costruire applicazioni in JS.</dd> + <dt><a href="https://www.youtube.com/user/codingmath"> Programmare matematica</a></dt> + <dd><span id="result_box" lang="it"><span>Una eccellente serie di video tutorial per imparare la matematica che devi conoscere per essere un programmatore valido, di</span></span> <a href="https://twitter.com/bit101">Keith Peters</a>.</dd> +</dl> diff --git a/files/it/learn/javascript/oggetti/basics/index.html b/files/it/learn/javascript/oggetti/basics/index.html new file mode 100644 index 0000000000..539df5c2e0 --- /dev/null +++ b/files/it/learn/javascript/oggetti/basics/index.html @@ -0,0 +1,242 @@ +--- +title: Basi degli oggetti JavaScript +slug: Learn/JavaScript/Oggetti/Basics +translation_of: Learn/JavaScript/Objects/Basics +--- +<div>{{LearnSidebar}}</div> + +<div>{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</div> + +<p class="summary">Nel primo articolo sugli oggetti JavaScript, vedremo la sintassi fondamentale degli oggetti JavaScript, e rivedremo alcune funzionalità di JavaScript che abbiamo già esamintato in precedenza in questo corso, rimarcando il fatto che molte delle funzionalità che abbiamo già incontrato son di fatto oggetti.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerequisiti:</th> + <td>Conoscenza basilare dei computers, comprensione di base di HTML e CSS, familiarità con le basi di JavaScript (vedi <a href="/en-US/docs/Learn/JavaScript/First_steps">Primi passi</a> e <a href="/en-US/docs/Learn/JavaScript/Building_blocks">Costruire blocchi</a>).</td> + </tr> + <tr> + <th scope="row">Obiettivo:</th> + <td>Capire le basi della teoria che stà dietro alla programmazione object-oriented, come questa si relazione con JavaScript ("la maggior parte delle cose sono oggetti"), e come incominciare a lavorare con gli oggetti JavaScript.</td> + </tr> + </tbody> +</table> + +<h2 id="Basi_degli_oggetti">Basi degli oggetti</h2> + +<p>Un oggetto è una collezione di dati e/o funzionalità correlati (che di solito consiste in alcune variabili e funzioni — che sono chiamate proprietà e metodi quando fanno parte di oggetti.) Proviamo con un esempio per vedere come si comportano.</p> + +<p>Per incomiciare, facciamo una copia locale del nostro file <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs.html">oojs.html</a>. Questo contiene un piccolissimo — elemento {{HTMLElement("script")}} che possiamo usare per scrivere il nostro sorgente, un elemento {{HTMLElement("input")}} per insrire istruzioni di esempio quando la pagina viene visualizzata, alcune definizioni di variabili, ed una funzione che invia ciò che si inserisce in input in un elemento {{HTMLElement("p")}}. Useremo questo come base per esplorare i concetti fondamentali della sintassi degli oggetti.</p> + +<p>Come molte cose in JavaScript, creare un oggetto spesso inizia definendo ed inizializzando una variabile. Prova ad inserire ciò che segue sotto al codice JavaScript già presente nel file, quindi salva e ricarica:</p> + +<pre class="brush: js">var person = {};</pre> + +<p>Se scrivi person nella casella di testo e premi il pulsante, dovresti ottenere il seguente risulatato:</p> + +<pre class="brush: js">[object Object]</pre> + +<p>Congratulazioni, hai appena creato il tuo primo oggetto. Ben fatto! Ma questo è un oggetto vuoto, perciò non ci possiamo fare molto. Aggiorniamo il nostro oggetto in questo modo:</p> + +<pre class="brush: js">var person = { + name: ['Bob', 'Smith'], + age: 32, + gender: 'male', + interests: ['music', 'skiing'], + bio: function() { + alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.'); + }, + greeting: function() { + alert('Hi! I\'m ' + this.name[0] + '.'); + } +}; +</pre> + +<p>Dopo aver salvato e ricaricato la pagina, prova ad inserire alcuni di questi nella casella di input:</p> + +<pre class="brush: js">person.name[0] +person.age +person.interests[1] +person.bio() +person.greeting()</pre> + +<p>Ora hai ottenuto alcuni dati e funzionalità nel tuo oggetto, ed ora puoi accedere ad essi con alcune sintassi semplici e graziose!</p> + +<div class="note"> +<p><strong>Nota</strong>: Se hai problemi ad ottenere questo risultato, prova comparare quello che hai scritto con la nostra versione — vedi <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-finished.html">oojs-finished.html</a> (e anche <a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-finished.html">la versione funzionante</a>). Un errore comune quando si inizia con gli oggetti è quello di mettere una virgola dopo l'ultimo elenemto — questo genera un errore.</p> +</div> + +<p>Quindi che cosa è successo qui? Bene, un oggetto è composto da svariati membri, ogniuno dei quali ha un nome (es. name e age sopra), ed un valore (es, <code>['Bob', 'Smith']</code> e <code>32</code>). Ogni coppia nome/valore deve essere separata da una virgola, ed ogni nome e valore devono essere separati dai due punti. La sintassi segue sempre questo schema:</p> + +<pre class="brush: js">var objectName = { + member1Name: member1Value, + member2Name: member2Value, + member3Name: member3Value +}</pre> + +<p>Il valore di un membro di un oggetto può essere qualsiasi cosa — nel nostro oggetto persona abbiamo una strigna, un numero, due array e due funzioni. I primi quatto elementi sono dati e ad essi ci si riferisce come le proprietà <strong>(properties)</strong> del oggetto. Gli ultimi due elementi sono funzioni che consentono all'oggetto di fare qualcosa con i dati, e ad esse ci si riferisce come i metodi <strong>(methods)</strong> dell'oggetto.</p> + +<p>Un oggetto come questo viene considerato un <strong>oggetto letterale</strong> — noi abbiamo scritto letteralmente il conenuto dell'oggetto nel momento che lo abbiamo creato. Questo è in contrasto con l'istanziazione di oggetti da classi, che vedremo un po' più avanti.</p> + +<p>È molto comune creare oggetti letterali quando si desidera trasferire una serie di dati relazionati e strutturati in qualche maniera, ad esempio per inviare richieste al server per inserire i dati nel database. Inviare un singolo oggetto è molto più efficiente che inviare i dati individualmente, ed è più facile lavorarci rispetto agli array, perché i dati vengono identificati per nome.</p> + +<h2 id="Notazione_puntata">Notazione puntata</h2> + +<p>Sopra, abbiamo acceduto alle proprietà ed ai metodi degli oggetti utilizzando la notazione puntata. Il nome dell'oggetto (person) serve da <strong>namespace</strong> — e deve essere insirito prima per accedere a qualsiasi cosa <strong>incapsulata</strong> nell'oggetto. Quindi si scrive il punto seguito dell'elemento a cui si vuole accedere — <br> + questo può essere il nome di una proprietà semplice, un elemento di una proprietà di tipo array, o una chiamata ad uno dei metodi dell oggetto, ad esempio:</p> + +<pre class="brush: js">person.age +person.interests[1] +person.bio()</pre> + +<h3 id="Namespaces_nidificati">Namespaces nidificati</h3> + +<p>È anche possibile assegnare un altro oggetto ad un membro di un oggetto. Ad esempio prova a cambiare la property name da</p> + +<pre class="brush: js">name: ['Bob', 'Smith'],</pre> + +<p>a</p> + +<pre class="brush: js">name : { + first: 'Bob', + last: 'Smith' +},</pre> + +<p>In questo modo abbiamo effettivamente creato un <strong>sotto-namespace</strong>. Può sembrare complesso, ma non lo è veramente — per accedere a questi devi solo concatenare un ulteriore passo alla fine con un altro punto. Prova questi:</p> + +<pre class="brush: js">person.name.first +person.name.last</pre> + +<p><strong>Importante</strong>: A questo punto devi anche cambiare il codice dei tuoi metodi e cambiare ogni istanza di</p> + +<pre class="brush: js">name[0] +name[1]</pre> + +<p>con</p> + +<pre class="brush: js">name.first +name.last</pre> + +<p>Altrimenti i tuoi metodi non funzioneranno più.</p> + +<h2 id="Notazione_con_parentesi_quadre">Notazione con parentesi quadre</h2> + +<p>C'è un altro modo per accedere alle proprietà degli oggetti — usando la notazione delle parentesi quadre. Invece di usare questi:</p> + +<pre class="brush: js">person.age +person.name.first</pre> + +<p>Puoi usare</p> + +<pre class="brush: js">person['age'] +person['name']['first']</pre> + +<p>Questo assomiglia molto al modo in cui accedi agli elementi di un array, ed è sostanzialmente la stessa cosa — invece di usare un indice numerico per scegliere un elemento, stai usando il nome associato ad ogni valore membro. Non c'è da meravigliarsi che gli oggetti a volte vengono chiamati <strong>array associativi</strong> — essi infatti associano le stringhe ai valori nello stesso modo in cui gli arrays associano i numeri ai valori.</p> + +<h2 id="Assegnare_i_membri_degli_oggetti">Assegnare i membri degli oggetti</h2> + +<p>Fino a qui abbiamo solo recuperato (<strong>get</strong>) valori dei menbri degli oggetti — si possono anche assegnare (<strong>set</strong>) i valori ai menbri degli oggetti semplicemente dichiarando i membri che si desidera assegnare (usando la notazione puntata o con quadre), cone ad esempio:</p> + +<pre class="brush: js">person.age = 45; +person['name']['last'] = 'Cratchit';</pre> + +<p>Prova ad inserire queste linee e poi rileggi i dati nuovamente per vedere che cosa è cambiato:</p> + +<pre class="brush: js">person.age +person['name']['last']</pre> + +<p>Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these:</p> + +<pre class="brush: js">person['eyes'] = 'hazel'; +person.farewell = function() { alert("Bye everybody!"); }</pre> + +<p>Ora possiamo provare i nostri nuovi membri:</p> + +<pre class="brush: js">person['eyes'] +person.farewell()</pre> + +<p>Un utile aspetto della notazione con parentesi quadre è che non solo può essere usata per assegnare valori dinamicamente, ma anche per assegnare i nomi dei mebri. Ad esempio se desideriamo che gli utenti siano in grado di assegnare tipi di dato personalizzati scrivendo il nome della proprietà ed il suo valore in due campi di input, possiamo oggenere questi valori in questo modo:</p> + +<pre class="brush: js">var myDataName = nameInput.value; +var myDataValue = nameValue.value;</pre> + +<p>e possiamo aggiungere questi nomi e valori nel nostro oggetto <code>person</code> in questo modo:</p> + +<pre class="brush: js">person[myDataName] = myDataValue;</pre> + +<p>Puoi testare questo aggiungendo le linee seguenti nel tuo codice appena prima della parentesi graffa chiusa nel oggetto <code>person</code>:</p> + +<pre class="brush: js">var myDataName = 'height'; +var myDataValue = '1.75m'; +person[myDataName] = myDataValue;</pre> + +<p>Ora prova s salvare e ricaricare la pagina ed inserisci ciò che segue nella casella di testo:</p> + +<pre class="brush: js">person.height</pre> + +<p>Non è possibile aggiungere proprità ad oggetti con il metodo descritto usando la notazione puntata, che accetta solo nomi aggiunti in modo letterale e non valori di variabili puntate da un nome.</p> + +<h2 id="Che_cos'è_this">Che cos'è "this"?</h2> + +<p>Forse ti sei accorto di qualcosa di leggermente strano nei nostri metodi. Guarda questo per esempio:</p> + +<pre class="brush: js">greeting: function() { + alert('Hi! I\'m ' + this.name.first + '.'); +}</pre> + +<p>Forse ti sei chiesto che cos'è "this". La parola chiave <code>this</code> fa riferimento all'oggetto in cui abbiamo scritto il codice — perciò in questo caso <code>this</code> è equivalente a <code>person</code>. Quindi perché non scrivere invece semplicemente <code>person</code>? Come vedrai nell'articolo <a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript per principianti</a> quando incominceremo a creare costruttori ecc., <code>this</code> è molto utile — perché garantisce sempre che venga trovato il valore corretto quando il contesto cambia (es. due diverse istanze dell'oggetto <code>person</code> possono avere nomi diversi, ma vogliamo accedere al nome corretto quando vogliamo fargli gli auguri).</p> + +<p>Proviamo ad illustrare ciò che intendiamo con un paio di oggetti <code>person</code> semplificati:</p> + +<pre class="brush: js">var person1 = { + name: 'Chris', + greeting: function() { + alert('Hi! I\'m ' + this.name + '.'); + } +} + +var person2 = { + name: 'Brian', + greeting: function() { + alert('Hi! I\'m ' + this.name + '.'); + } +}</pre> + +<p>In questo caso, <code>person1.greeting()</code> visualizza "Hi! I'm Chris."; e <code>person2.greeting()</code> "Hi! I'm Brian.", anche se il codice del metodo è esattamente identico. Come abbiamo detto prima, <code>this</code> fa riferimento al valore interno all'oggetto — questo non è molto importante per gli oggetti letterali scritti a mano, ma lo diventa quando gli oggetti vengono generati dinamicamente (per esempio usando i costruttori). Diventerà più chiaro in seguito.</p> + +<h2 id="Finora_hai_usato_oggetti_tutto_il_tempo">Finora hai usato oggetti tutto il tempo</h2> + +<p>Avendo provato questi esempi, probabilmente hai pensato che la notazione a punto fin qui usata è molto familiare. Questo perché l'hai già usata durante il corso! Tutte le volte che abbiamo lavorato con un esempio che usa le API built-in del browser o oggetti JavaScript, abbiamo usato oggetti, perché quelle funzionalità sono state costruite usando lo stesso tipo di strutture di oggetti che stiamo vedendo qui, anche se molto più complesse dei nostri semplici esempi.</p> + +<p>Quindi quando ha usato un metodo di stringa come:</p> + +<pre class="brush: js">myString.split(',');</pre> + +<p>Non hai fatto altro che usare un metodo disponibile in una istanza della classe <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></code>. Ogni volta che crei una stringa nel tuo codice, viene automaticamente creata una istanza di <code>String</code>, che ha ha disposizione alcuni metodi/proprietà comuni.</p> + +<p>Quando hai acceduto al modello di oggetto documento usando righe come queste:</p> + +<pre class="brush: js">var myDiv = document.createElement('div'); +var myVideo = document.querySelector('video');</pre> + +<p>Tu hai usato i metodi disponibili in una istanza della classe <code><a href="/en-US/docs/Web/API/Document">Document</a></code>. Per ogni pagina web caricara viene crata una istanza di <code>Document</code> chiamata document, che rappresenta l'intera struttura della pagina, il contenuto e le altre funzionalità come il suo URL. Nuovamente questo significa che ci sono diversi metodi/proprietà comuni disponibili.</p> + +<p>Questo è vero anche per molti degli altri oggetti/API built-in che hai usato — <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math">Math</a></code>, ecc.</p> + +<p>Nota che gli Oggetti/API built-in non sempre creano le istanze di oggetto automaticamente. Ad esempio, le <a href="/en-US/docs/Web/API/Notifications_API">Notifications API</a> — che consentono ai browsers moderni di attivare notifiche di sistema — richiedono che venga instanziato una nuova istanza utilizzando il costruttore per ogni notifica che vuoi avviare. Prova scrivendo questo nella tua console JavaScript:</p> + +<pre class="brush: js">var myNotification = new Notification('Hello!');</pre> + +<p>Spiegheremo i costruttori in un prossimo articolo.</p> + +<div class="note"> +<p><strong>Nota</strong>: È utile pensare al modo in cui gli oggetti comunicano come ad un <strong>passaggio di messaggi</strong> — quando un oggetto ha bisogno che un altro oggetto faccia qualcosa, spesso manda un messaggio all'altro oggetto usando uno dei suoi metodi, ed aspetta la risposta sottoforma di valore restituito.</p> +</div> + +<h2 id="Sommario">Sommario</h2> + +<p>Congratulazioni, hai raggiunto la fine del nostro primo artocolo sugli oggetti JS — ora dovresti avere una buona idesa di come lavorare con gli oggetti in JavaScript — compresa la creazione di tuoi semplici oggetti. Dovresti anche apprezzare che gli oggetti sono molto utili come strutture per memorizzare dati e funzionalità correlati — se hai provato a tenere traccia delle proprietà e dei metodi del nostro oggetto <code>person</code> in forma di variabili e funzioni separate, dovrebbe essere stato inefficente e frustrante, ed hai corso il rischio di confondere i dati con altre variabli con lo stesso nome. Gli oggetti ci permettono di tenere le informazioni confinate in modo sicuro nel proprio pacchetto senza rischio.</p> + +<p>Nel prossimo articolo incominceremo ad introdurre la teoria della programmazione object-oriented (OOP), ed in che modo queste tecniche possono essere usate in JavaScript.</p> + +<p>{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</p> diff --git a/files/it/learn/javascript/oggetti/index.html b/files/it/learn/javascript/oggetti/index.html new file mode 100644 index 0000000000..5fa859db74 --- /dev/null +++ b/files/it/learn/javascript/oggetti/index.html @@ -0,0 +1,51 @@ +--- +title: Introduzione agli oggetti in JavaScript +slug: Learn/JavaScript/Oggetti +tags: + - Articolo + - Guida + - JavaScript + - Oggetti + - Principiante + - Tutorial + - Verifica + - imparare +translation_of: Learn/JavaScript/Objects +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">In JavaScript molte cose sono oggetti, a partire da caratteristiche base di JavaScript come stringhe ed array, fino alle API del browser costruite in JavaScript. Potete anche creare i vostri oggetti, incapsulando funzioni e variabili tra loro correlate in pacchetti funzionalmente efficienti e che funzionano da comodi contenitori di dati. Se volete progredire nella vostra conoscenza di JavaScript, è importante comprendere la sua natura <em>object-oriented</em> (orientata agli oggetti), perciò abbiamo approntato questo modulo per aiutarvi. Qui parleremo in dettaglio della teoria e della sintassi degli oggetti; successivamente vedremo come creare i vostri oggetti personalizzati.</p> + +<h2 id="Prerequisiti">Prerequisiti</h2> + +<p>Prima di iniziare questo modulo, dovreste avere una qualche familiarità con HTML e CSS. Vi consigliamo di seguire i moduli <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Introduction">Introduzione a HTML</a> e <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduzione a CSS</a> prima di cimentarvi con JavaScript.</p> + +<p>Dovreste anche avere qualche familiarità con i fondamenti di JavaScript prima di affrontare in dettaglio gli oggetti in JavaScript. Prima di procedere con questo modulo vi consigliamo di seguire i moduli <a href="/en-US/docs/Learn/JavaScript/First_steps">Primi passi con JavaScript</a> e <a href="/en-US/docs/Learn/JavaScript/Building_blocks">JavaScript building blocks</a>.</p> + +<div class="note"> +<p><strong>Nota</strong>: Se state lavorando su un computer, tablet o altro dispositivo sul quale non fosse possibile creare i vostri file, potete sperimentare buona parte del codice di esempio in un programma di scrittura codice online, come ad esempio <a href="http://jsbin.com/">JSBin</a> o <a href="https://thimble.mozilla.org/">Thimble</a>.</p> +</div> + +<h2 id="Guide">Guide</h2> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/Basics">Fondamenti sugli oggetti</a></dt> + <dd>Nel primo articolo riguardante gli oggetti JavaScript vedremo la sintassi fondamentale degli oggetti, e rivisiteremo alcune caratteristiche di JavaScript che abbiamo già introdotto durante il corso, verificando che molte delle caratteristche con cui avete già avuto a che fare sono di fatto oggetti.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript per principianti</a></dt> + <dd>Una volta acquisite le basi ci focalizzeremo sul JavaScript orientato agli oggetti (<em>object-oriented JavaScript</em>, OOJS) — questo articolo illustra i fondamenti della programmazione orientata agli oggetti (<em>object-oriented programming</em>, OOP), per poi esplorare come JavaScript emuli le classi di oggetti tramite le funzioni costruttore, e come creare istanze di un oggetto .</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">Prototipi di oggetto (object prototypes)</a></dt> + <dd>I prototipi sono il meccanismo tramite il quale gli oggetti JavaScript ereditano caratteristiche tra di loro, e funzionano diversamente dai meccanismi di ereditarietà presenti nei classici linguaggi orientati agli oggetti. In questo articolo esploreremo questa differenza, spiegheremo come funzionano le catene di prototipi, e vedremo come la proprietà di prototipo può essere usata per aggiungere metodi a costruttori esistenti..</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance">Ereditarietà in JavaScript</a></dt> + <dd>Dopo aver spiegato buona parte delle frattaglie dell'OOJS, questo articolo mostra come creare classi di oggetti "figli" che ereditano caratteristiche dalle loro classi "antenate". Presentiamo inoltre alcuni consigli circa quando e dove potreste usare OOJS.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/JSON">Lavorare con i dati JSON</a></dt> + <dd>JavaScript Object Notation (JSON) è un formato standard per rappresentare dati strutturati come oggetti JavaScript. Esso è comunemente usato per rappresentare e trasmettere dati sui siti web (ad esempio inviare alcuni dati dal server al client, cosicché venga visualizzato in una pagina web). Poiché lo incontrerete piuttosto spesso, in quest'articolo vi daremo tutto ciò di cui avete bisogno per lavorare con JSON usando JavaScript, incluso come accedere agli elementi di dati in un oggetto JSON e come scrivere il vostro JSON.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/Object_building_practice">Pratica della costruzione di oggetti</a></dt> + <dd>Negli articoli precedenti abbiamo descritto la teoria essenziale degli oggetti JavaScript e i dettagli sulla sintassi, dandovi una base solida da cui Partire. In questo articolo ci cimenteremo in un esercizio pratico, in cui costruirete oggetti JavaScript personalizzati che producono qualcosa di divertente e colorato — alcune palline colorate rimbalzanti.</dd> +</dl> + +<h2 id="Verifiche">Verifiche</h2> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">Aggiungere caratteristiche alla demo "bouncing balls"</a></dt> + <dd>In questa verifiche userete la demo delle palline rimbalzanti come punto di partenza, aggiungendole alcune nuove ed interessanti caratteristiche.</dd> +</dl> diff --git a/files/it/learn/javascript/oggetti/json/index.html b/files/it/learn/javascript/oggetti/json/index.html new file mode 100644 index 0000000000..71cf166e15 --- /dev/null +++ b/files/it/learn/javascript/oggetti/json/index.html @@ -0,0 +1,345 @@ +--- +title: Lavorare con JSON +slug: Learn/JavaScript/Oggetti/JSON +translation_of: Learn/JavaScript/Objects/JSON +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}</div> + +<p class="summary">JavaScript Object Notation (JSON) è un formato testuale standard, usato per rappresentare dati strutturati basati sulla sintassi degli oggetti in JavaScript. E' usato comunemente per la trasmissione dati nelle applicazioni web (ad es. inviare dati dal server al client in modo da visualizzarli in una pagina web o viceversa). Ti imbatterai abbastanza spesso in questo formato, così in questo articolo ti forniremo tutto ciò che ti occorre per lavorare con JSON usando JavaScript, incluso la lettura (parsing) del JSON in modo da accedere ai dati in esso contenuti, così come a generare JSON.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerequisiti:</th> + <td>Conoscenza informatica di base, comprensione base di HTML e CSS, familiarità con i concetti base di JavaScript (vedi <a href="/en-US/docs/Learn/JavaScript/First_steps">Primi passi</a> e <a href="/en-US/docs/Learn/JavaScript/Building_blocks">Costruzione blocchi</a>) e con i concetti base degli oggetti JS (vedi <a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduzione agli oggetti</a>).</td> + </tr> + <tr> + <th scope="row">Obiettivi:</th> + <td>Comprendere il funzionamento dei dati megorizzati in JSON e creare i tuoi oggetti JSON.</td> + </tr> + </tbody> +</table> + +<h2 id="No_davvero_cosè_JSON">No, davvero, cos'è JSON?</h2> + +<p>{{glossary("JSON")}} è un formato dati testuale che segue la sintassi degli oggetti JavaScript, reso popolare da <a href="https://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a>. Anche se richiama da vicino la sintassi letterale degli oggetti JavaScript, può essere usato indipendentemente da JavaScript, e molti ambienti di programmazione supportano la lettura (parsing) e la generazione di JSON.</p> + +<p>JSON esiste sotto forma di una stringa — utile quando vuoi trasmettere dati in una rete. Deve essere poi convertito in un oggetto javaScript nativo quando vuoi accedere ai dati che rappresenta. La conversione tra i due è piuttosto banale — grazie ai metodi dell'oggetto globale <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> di JavaScript.</p> + +<div class="note"> +<p><strong>Nota</strong>: Convertire una stringa in un oggetto nativo è chiamata <em>deserializzazione</em>, mentre convertire un oggetto nativo in una stringa in modo da poterlo trasmettere in rete, è chiamata <em>serializzazione</em>.</p> +</div> + +<p>Un oggetto JSON object può essere memorizzato in un file dedicato, essenzialmente un file di testo con estensione <code>.json</code>, e un {{glossary("tipo MIME")}} <code>application/json</code>.</p> + +<h3 id="Struutura_di_un_JSON">Struutura di un JSON </h3> + +<p>Come descritto sopra, un JSON non è altro che una stringa il cui formato è molto simile al formato letterale di un oggetto JavaScript. E' possibile includere in JSON gli stessi tipi di dato base possibili in un oggetto standard di JavaScript — stringhe, numeri, arrays, booleani e altri oggetti letterali. Questo ti consente di costruire una gerarchia dei dati, ad esempio:</p> + +<pre class="brush: json">{ + "squadName": "Super hero squad", + "homeTown": "Metro City", + "formed": 2016, + "secretBase": "Super tower", + "active": true, + "members": [ + { + "name": "Molecule Man", + "age": 29, + "secretIdentity": "Dan Jukes", + "powers": [ + "Radiation resistance", + "Turning tiny", + "Radiation blast" + ] + }, + { + "name": "Madame Uppercut", + "age": 39, + "secretIdentity": "Jane Wilson", + "powers": [ + "Million tonne punch", + "Damage resistance", + "Superhuman reflexes" + ] + }, + { + "name": "Eternal Flame", + "age": 1000000, + "secretIdentity": "Unknown", + "powers": [ + "Immortality", + "Heat Immunity", + "Inferno", + "Teleportation", + "Interdimensional travel" + ] + } + ] +}</pre> + +<p>Se carichiamo questo oggetto in un programma, processato in una variabile chiamata <code>superHeroes</code> per esempio, potremmo accedere ai dati che contiene usando la medesima notazione punto/parentesi vista nell'articolo <a href="/en-US/docs/Learn/JavaScript/Objects/Basics">Fondamentali degli oggetti JavaScript</a>. Per esempio:</p> + +<pre class="brush: js">superHeroes.homeTown +superHeroes['active']</pre> + +<p>Per accedere ai dati gerarchicamente inferiori, occorre semplicemente concatenare i nome delle proprietà e gli indici degli array. Ad esempio, per accedere al terzo superpotere del secondo eroe nella lista dei membri, procedi come segue:</p> + +<pre class="brush: js">superHeroes['members'][1]['powers'][2]</pre> + +<ol> + <li>Per primo abbiamo il nome della variabile — <code>superHeroes</code>.</li> + <li>All'interno della variabile vogliamo accedere alla proprietà <code>members</code>, così utilizziamo <code>["members"]</code>.</li> + <li><code>members</code> contiene un array popolato da oggetti. Noi vogliamo accedere al secondo oggetto dell'array, quindi usiamo <code>[1]</code>.</li> + <li>all'interno dell'oggetto così trovato, vogliamo poi accedere alla proprietà <code>powers</code> e per ciò usiamo <code>["powers"]</code>.</li> + <li>La proprietà <code>powers</code> contiene a sua volta un array in cui sono elencate i superpoteri dell'eroe selezionato. Noi vogliamo la terza in lista, usiamo quindi <code>[2]</code>.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: Abbiamo reso disponibile il JSON visto sopra, in una variabile del nostro esempio <a href="http://mdn.github.io/learning-area/javascript/oojs/json/JSONTest.html">JSONTest.html</a> (vedi il <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/JSONTest.html">codice sorgente</a>). Prova a caricarlo e poi accedi alla variabile dalla console JavaScript del tuo browser.</p> +</div> + +<h3 id="Arrays_as_JSON">Arrays as JSON</h3> + +<p>Above we mentioned that JSON text basically looks like a JavaScript object, and this is mostly right. The reason we said "mostly right" is that an array is also valid JSON, for example:</p> + +<pre class="brush: json">[ + { + "name": "Molecule Man", + "age": 29, + "secretIdentity": "Dan Jukes", + "powers": [ + "Radiation resistance", + "Turning tiny", + "Radiation blast" + ] + }, + { + "name": "Madame Uppercut", + "age": 39, + "secretIdentity": "Jane Wilson", + "powers": [ + "Million tonne punch", + "Damage resistance", + "Superhuman reflexes" + ] + } +]</pre> + +<p>The above is perfectly valid JSON. You'd just have to access array items (in its parsed version) by starting with an array index, for example <code>[0]["powers"][0]</code>.</p> + +<h3 id="Other_notes">Other notes</h3> + +<ul> + <li>JSON is purely a data format — it contains only properties, no methods.</li> + <li>JSON requires double quotes to be used around strings and property names. Single quotes are not valid.</li> + <li>Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like <a href="http://jsonlint.com/">JSONLint</a>.</li> + <li>JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be a valid JSON object.</li> + <li>Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.</li> +</ul> + +<h2 id="Active_learning_Working_through_a_JSON_example">Active learning: Working through a JSON example</h2> + +<p>So, let's work through an example to show how we could make use of some JSON data on a website.</p> + +<h3 id="Getting_started">Getting started</h3> + +<p>To begin with, make local copies of our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes.html">heroes.html</a> and <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/style.css">style.css</a> files. The latter contains some simple CSS to style our page, while the former contains some very simple body HTML:</p> + +<pre class="brush: html"><header> +</header> + +<section> +</section></pre> + +<p>Plus a {{HTMLElement("script")}} element to contain the JavaScript code we will be writing in this exercise. At the moment it only contains two lines, which grab references to the {{HTMLElement("header")}} and {{HTMLElement("section")}} elements and store them in variables:</p> + +<pre class="brush: js">const header = document.querySelector('header'); +const section = document.querySelector('section');</pre> + +<p>We have made our JSON data available on our GitHub, at <a href="https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json">https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json</a>.</p> + +<p>We are going to load it into our page, and use some nifty DOM manipulation to display it, like this:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13857/json-superheroes.png" style="display: block; margin: 0 auto;"></p> + +<h3 id="Obtaining_the_JSON">Obtaining the JSON</h3> + +<p>To obtain the JSON, we use an API called {{domxref("XMLHttpRequest")}} (often called <strong>XHR</strong>). This is a very useful JavaScript object that allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning that we can update small sections of content without having to reload the entire page. This has led to more responsive web pages, and sounds exciting, but it is beyond the scope of this article to teach it in much more detail.</p> + +<ol> + <li>To start with, we store the URL of the JSON we want to retrieve in a variable. Add the following at the bottom of your JavaScript code: + <pre class="brush: js">let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';</pre> + </li> + <li>To create a request, we need to create a new request object instance from the <code>XMLHttpRequest</code> constructor, using the <code>new</code> keyword. Add the following below your last line: + <pre class="brush: js">let request = new XMLHttpRequest();</pre> + </li> + <li>Now we need to open the request using the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/open">open()</a></code> method. Add the following line: + <pre class="brush: js">request.open('GET', requestURL);</pre> + + <p>This takes at least two parameters — there are other optional parameters available. We only need the two mandatory ones for this simple example:</p> + + <ul> + <li>The HTTP method to use when making the network request. In this case <code><a href="/en-US/docs/Web/HTTP/Methods/GET">GET</a></code> is fine, as we are just retrieving some simple data.</li> + <li>The URL to make the request to — this is the URL of the JSON file that we stored earlier.</li> + </ul> + </li> + <li>Next, add the following two lines — here we are setting the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/responseType">responseType</a></code> to JSON, so that XHR knows that the server will be returning JSON, and that this should be converted behind the scenes into a JavaScript object. Then we send the request with the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/send">send()</a></code> method: + <pre class="brush: js">request.responseType = 'json'; +request.send();</pre> + </li> + <li>The last bit of this section involves waiting for the response to return from the server, then dealing with it. Add the following code below your previous code: + <pre class="brush: js">request.onload = function() { + const superHeroes = request.response; + populateHeader(superHeroes); + showHeroes(superHeroes); +}</pre> + </li> +</ol> + +<p>Here we are storing the response to our request (available in the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/response">response</a></code> property) in a variable called <code>superHeroes</code>; this variable now contains the JavaScript object based on the JSON! We are then passing that object to two function calls — the first one fills the <<code>header></code> with the correct data, while the second one creates an information card for each hero on the team, and inserts it into the <code><section></code>.</p> + +<p>We have wrapped the code in an event handler that runs when the load event fires on the request object (see <code><a href="/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload">onload</a></code>) — this is because the load event fires when the response has successfully returned; doing it this way guarantees that <code>request.response</code> will definitely be available when we come to try to do something with it.</p> + +<h3 id="Populating_the_header">Populating the header</h3> + +<p>Now that we've retrieved the JSON data and converted it into a JavaScript object, let's make use of it by writing the two functions we referenced above. First of all, add the following function definition below the previous code:</p> + +<pre class="brush: js">function populateHeader(jsonObj) { + const myH1 = document.createElement('h1'); + myH1.textContent = jsonObj['squadName']; + header.appendChild(myH1); + + const myPara = document.createElement('p'); + myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed']; + header.appendChild(myPara); +}</pre> + +<p>We named the parameter <code>jsonObj</code>, to remind ourselves that this JavaScript object originated from JSON. Here we first create an {{HTMLElement("h1")}} element with <code><a href="/en-US/docs/Web/API/Document/createElement">createElement()</a></code>, set its <code><a href="/en-US/docs/Web/API/Node/textContent">textContent</a></code> to equal the <code>squadName</code> property of the object, then append it to the header using <code><a href="/en-US/docs/Web/API/Node/appendChild">appendChild()</a></code>. We then do a very similar operation with a paragraph: create it, set its text content and append it to the header. The only difference is that its text is set to a concatenated string containing both the <code>homeTown</code> and <code>formed</code> properties of the object.</p> + +<h3 id="Creating_the_hero_information_cards">Creating the hero information cards</h3> + +<p>Next, add the following function at the bottom of the code, which creates and displays the superhero cards:</p> + +<pre class="brush: js">function showHeroes(jsonObj) { + const heroes = jsonObj['members']; + + for (let i = 0; i < heroes.length; i++) { + const myArticle = document.createElement('article'); + const myH2 = document.createElement('h2'); + const myPara1 = document.createElement('p'); + const myPara2 = document.createElement('p'); + const myPara3 = document.createElement('p'); + const myList = document.createElement('ul'); + + myH2.textContent = heroes[i].name; + myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity; + myPara2.textContent = 'Age: ' + heroes[i].age; + myPara3.textContent = 'Superpowers:'; + + const superPowers = heroes[i].powers; + for (let j = 0; j < superPowers.length; j++) { + const listItem = document.createElement('li'); + listItem.textContent = superPowers[j]; + myList.appendChild(listItem); + } + + myArticle.appendChild(myH2); + myArticle.appendChild(myPara1); + myArticle.appendChild(myPara2); + myArticle.appendChild(myPara3); + myArticle.appendChild(myList); + + section.appendChild(myArticle); + } +}</pre> + +<p>To start with, we store the <code>members</code> property of the JavaScript object in a new variable. This array contains multiple objects that contain the information for each hero.</p> + +<p>Next, we use a <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#The_standard_for_loop">for loop</a> to loop through each object in the array. For each one, we:</p> + +<ol> + <li>Create several new elements: an <code><article></code>, an <code><h2></code>, three <code><p></code>s, and a <code><ul></code>.</li> + <li>Set the <code><h2></code> to contain the current hero's <code>name</code>.</li> + <li>Fill the three paragraphs with their <code>secretIdentity</code>, <code>age</code>, and a line saying "Superpowers:" to introduce the information in the list.</li> + <li>Store the <code>powers</code> property in another new constant called <code>superPowers</code> — this contains an array that lists the current hero's superpowers.</li> + <li>Use another <code>for</code> loop to loop through the current hero's superpowers — for each one we create an <code><li></code> element, put the superpower inside it, then put the <code>listItem</code> inside the <code><ul></code> element (<code>myList</code>) using <code>appendChild()</code>.</li> + <li>The very last thing we do is to append the <code><h2></code>, <code><p></code>s, and <code><ul></code> inside the <code><article></code> (<code>myArticle</code>), then append the <code><article></code> inside the <code><section></code>. The order in which things are appended is important, as this is the order they will be displayed inside the HTML.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: If you are having trouble getting the example to work, try referring to our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes-finished.html">heroes-finished.html</a> source code (see it <a href="http://mdn.github.io/learning-area/javascript/oojs/json/heroes-finished.html">running live</a> also.)</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the <a href="http://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json">superheroes.json</a> file open in another tab or your text editor, and refer to it as you look at our JavaScript. You should also refer back to our <a href="/en-US/docs/Learn/JavaScript/Objects/Basics">JavaScript object basics</a> article for more information on dot and bracket notation.</p> +</div> + +<h2 id="Converting_between_objects_and_text">Converting between objects and text</h2> + +<p>The above example was simple in terms of accessing the JavaScript object, because we set the XHR request to convert the JSON response directly into a JavaScript object using:</p> + +<pre class="brush: js">request.responseType = 'json';</pre> + +<p>But sometimes we aren't so lucky — sometimes we receive a raw JSON string, and we need to convert it to an object ourselves. And when we want to send a JavaScript object across the network, we need to convert it to JSON (a string) before sending. Luckily, these two problems are so common in web development that a built-in <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> object is available in browsers, which contains the following two methods:</p> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">parse()</a></code>: Accepts a JSON string as a parameter, and returns the corresponding JavaScript object.</li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringify()</a></code>: Accepts an object as a parameter, and returns the equivalent JSON string form.</li> +</ul> + +<p>You can see the first one in action in our <a href="http://mdn.github.io/learning-area/javascript/oojs/json/heroes-finished-json-parse.html">heroes-finished-json-parse.html</a> example (see the <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes-finished-json-parse.html">source code</a>) — this does exactly the same thing as the example we built up earlier, except that we set the XHR to return the raw JSON text, then used <code>parse()</code> to convert it to an actual JavaScript object. The key snippet of code is here:</p> + +<pre class="brush: js">request.open('GET', requestURL); +request.responseType = 'text'; // now we're getting a string! +request.send(); + +request.onload = function() { + const superHeroesText = request.response; // get the string from the response + const superHeroes = JSON.parse(superHeroesText); // convert it to an object + populateHeader(superHeroes); + showHeroes(superHeroes); +}</pre> + +<p>As you might guess, <code>stringify()</code> works the opposite way. Try entering the following lines into your browser's JavaScript console one by one to see it in action:</p> + +<pre class="brush: js">let myJSON = { "name": "Chris", "age": "38" }; +myJSON +let myString = JSON.stringify(myJSON); +myString</pre> + +<p>Here we're creating a JavaScript object, then checking what it contains, then converting it to a JSON string using <code>stringify()</code> — saving the return value in a new variable — then checking it again.</p> + +<h2 id="Test_your_skills!">Test your skills!</h2> + +<p>You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see <a href="/en-US/docs/Learn/JavaScript/Objects/Test_your_skills:_JSON">Test your skills: JSON</a>.</p> + +<h2 id="Summary">Summary</h2> + +<p>In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article, we'll begin looking at object-oriented JavaScript.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON object reference page</a></li> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest object reference page</a></li> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li> + <li><a href="/en-US/docs/Web/HTTP/Methods">HTTP request methods</a></li> + <li><a href="http://json.org">Official JSON web site with link to ECMA standard</a></li> +</ul> + +<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics">Object basics</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript for beginners</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance">Inheritance in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON">Working with JSON data</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_building_practice">Object building practice</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">Adding features to our bouncing balls demo</a></li> +</ul> |