nested objects = objects inside of other Objects
- allows you to represent more complex data structures
- child object is enclosed by a parent object
person{address{}, contactInfo{}};
shoppingCart{keyboard{}, Mouse{}, Monitor{}}Example:
// 定义一个对象 person,里面包含各种类型的数据
const person = {
fullName: "spongebob squarepants",
age: 30,
isStudent: true,
hobbies: ["karate", "jellyfishing", "cooking"],
address: {
street: "124 Conch St.",
city: "Bikini Bottom",
country: "Int. Water",
}
}
console.log(person.fullName); //spongebob squarepants
console.log(person.age);//30
console.log(person.isStudent);//true
// 访问嵌套的数组属性
console.log(person.hobbies[2]);//cooking
// 访问嵌套对象本身 输出整个 address 对象:
console.log(person.address);//{object}}
// 访问嵌套对象的单个属性
console.log(person.address.country);//Int. Water
//遍历nested object 使用 for...in 循环可以遍历对象中的所有键 (key)
for(const property in person.address){
console.log(person.address[property])
}
// 输出顺序如下:
//124 Conch St.
//Bikini Bottom
//Int. WaterExample more complex:
// ====================== 定义 Person 类 ======================
class Person{
constructor(name, age, ...address){
// name 和 age 是普通属性
this.name = name;
this.age = age;
// ...address 是 “剩余参数”(Rest Parameter)
// 它会把后面所有参数收集成一个数组
// 例如: ["124 Conch St.", "Bikini Bottom", "Int. Waters"]
// 使用 Address 类来创建一个嵌套对象
// 通过展开运算符 ...address 把数组解包传入 Address 的构造函数
this.address = new Address(...address);
}
}
// ====================== 定义 Address 类 ======================
class Address{
constructor(street, city, country){
this.street = street; // 街道
this.city = city; // 城市
this.country = country; // 国家
}
}
// ====================== 创建 Person 对象 ======================
// 传入参数:name, age, street, city, country
const person1 = new Person("Spongebob", 30, "124 Conch St.", "Bikini Bottom", "Int. Waters");
const person2 = new Person("Patrick", 37, "128 Conch St.", "Bikini Bottom", "Int. Waters");
const person3 = new Person("Squidward", 45, "126 Conch St.", "Bikini Bottom", "Int. Waters");
// ====================== 测试输出 ======================
// 打印整个 person1 对象
console.log(person1);
/*
输出结果:
Person {
name: 'Spongebob',
age: 30,
address: Address {
street: '124 Conch St.',
city: 'Bikini Bottom',
country: 'Int. Waters'
}
}
*/
// 打印嵌套对象 address
console.log(person1.address);
/*
输出结果:
Address {
street: '124 Conch St.',
city: 'Bikini Bottom',
country: 'Int. Waters'
}
*/
// 访问嵌套对象的属性
console.log(person1.address.street); // 输出: 124 Conch St.