Oggetti
Scorri per mostrare il menu
Gli oggetti sono una caratteristica fondamentale in JavaScript che consente di raggruppare dati e valori correlati. Un oggetto è una raccolta di proprietà, dove ciascuna proprietà ha un nome (chiamato chiave) e un valore.
Questa struttura chiave-valore rende gli oggetti ideali per rappresentare entità del mondo reale e organizzare le informazioni in modo flessibile. Un oggetto si definisce utilizzando le parentesi graffe {} e ogni proprietà viene scritta come una coppia: la chiave (come stringa o identificatore), seguita da due punti e poi dal valore. Più proprietà sono separate da virgole.
12345678// Creating an object to represent a user profile const userProfile = { username: "coder123", age: 28, email: "coder123@example.com", isActive: true }; console.log(JSON.stringify(userProfile));
È possibile accedere alle proprietà di un oggetto utilizzando la dot notation oppure la bracket notation. Ad esempio, userProfile.username restituisce il valore "coder123".
12345678910111213const userProfile = { username: "coder123", age: 28, email: "coder123@example.com", isActive: true }; console.log(JSON.stringify(userProfile)); // Accessing object properties using dot notation console.log(userProfile.username); // Dot notation // Accessing object properties using bracket notation console.log(userProfile["email"]); // Bracket notation
Per aggiornare una proprietà, assegnare semplicemente un nuovo valore: userProfile.age = 29;. Per aggiungere una nuova proprietà, assegnarla direttamente: userProfile.location = "New York";.
123456789101112131415const userProfile = { username: "coder123", age: 28, email: "coder123@example.com", isActive: true }; console.log(JSON.stringify(userProfile)); // Update the existing 'age' property userProfile.age = 29; // Add a new 'location' property userProfile.location = "New York"; console.log(JSON.stringify(userProfile));
Gli oggetti permettono di organizzare dati correlati sotto una singola variabile, rendendo il codice più leggibile e facile da mantenere.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione