Home > Web Front-end > JS Tutorial > Object Literals

Object Literals

王林
Release: 2024-08-07 10:01:00
Original
760 people have browsed it

Object Literals

Objects are collections of key-value pairs (properties).

To create an object we can do as follows:

let person = {
   firstName: 'Megan',
   isOnVacation: true,
   favFoods: ['plum', 'salad', 'fritos']
}
Copy after login

To access values within the object we can:

console.log(person.isOnVacation); // true
console.log(person['isOnVacation']); // true
Copy after login

We can also make an object that contains objects:

let student = {
   name: 'Jimmy',
   exams: {
      artFinal: 'A',
      mathFinal: 88
   }
}
Copy after login

To access a value in the object's object, we can:

console.log(student.exams.artFinal); // 'A'
Copy after login

Also, we can make arrays containing objects:

let friends = [
   {
      name: 'Sorour',
      favColor: 'blue',
      metAt: 'college'
   },
   {
      name: 'Timothy',
      favColor: 'red',
      metAt: 'Starbucks'
   }
];
Copy after login

To access a value in the second object, we can call:

console.log(friends[1].favColor); // 'red'
Copy after login

To update a value in the second object, we can:

friends[1].name = 'Tim';

console.log(friends[1].name); // Tim
Copy after login

The above is the detailed content of Object Literals. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template