Appearance
Objects
In JavaScript, an object is an unordered collection data type that consists of key-value pairs. Objects are used to describe real-world entities. For example, to describe a mischievous child named "Xiao Ming," we can define an object with several properties:
javascript
let xiaoming = {
name: '小明',
birth: 1990,
school: 'No.1 Middle School',
height: 1.70,
weight: 65,
score: null
};
In JavaScript, an object is represented with {...}
, and key-value pairs are defined in the format key: value
, separated by commas. Note that the last key-value pair should not have a trailing comma, as it may cause errors in some browsers (like older versions of IE).
Accessing Properties
You can access properties using the dot (.
) operator, which requires that the property name is a valid variable name:
javascript
xiaoming.name; // '小明'
xiaoming.birth; // 1990
If a property name contains special characters or hyphens, you must enclose it in quotes and use bracket notation:
javascript
let xiaohong = {
name: '小红',
'middle-school': 'No.1 Middle School'
};
xiaohong['middle-school']; // 'No.1 Middle School'
xiaohong['name']; // '小红'
While you can access properties with both dot and bracket notation, using dot notation is simpler for standard variable names.
Dynamic Nature
JavaScript objects are dynamic, allowing you to freely add or delete properties:
javascript
let xiaoming = {
name: '小明'
};
xiaoming.age; // undefined
xiaoming.age = 18; // Adds the age property
delete xiaoming.age; // Deletes the age property
If you access a non-existent property, JavaScript returns undefined
without throwing an error:
javascript
'use strict';
let xiaoming = {
name: '小明'
};
console.log(xiaoming.name); // '小明'
console.log(xiaoming.age); // undefined
Checking for Properties
To check if an object has a certain property, you can use the in
operator:
javascript
'name' in xiaoming; // true
'grade' in xiaoming; // false
Be cautious, as in
checks both own properties and inherited properties:
javascript
'toString' in xiaoming; // true
To determine if a property is directly on the object (not inherited), use hasOwnProperty()
:
javascript
xiaoming.hasOwnProperty('name'); // true
xiaoming.hasOwnProperty('toString'); // false
Summary
JavaScript objects are versatile data structures that allow for the dynamic management of properties, providing a powerful way to represent real-world entities in code.