// 示例代码:解构对象
// 定义一个对象
const person = {
name: 'Alice',
age: 25,
address: {
city: 'Beijing',
country: 'China'
}
};
// 解构对象的基本用法
const { name, age } = person;
console.log(name); // 输出: Alice
console.log(age); // 输出: 25
// 解构嵌套对象
const { address: { city, country } } = person;
console.log(city); // 输出: Beijing
console.log(country); // 输出: China
// 给解构的变量指定默认值
const { job = 'Engineer' } = person;
console.log(job); // 输出: Engineer (因为 person 对象中没有 job 属性)
// 将解构的属性赋值给新的变量名
const { name: fullName, age: yearsOld } = person;
console.log(fullName); // 输出: Alice
console.log(yearsOld); // 输出: 25
{ name, age }
可以直接从 person
对象中提取 name
和 age
属性,并将其赋值给同名变量。address: { city, country }
进行深层次的解构。job = 'Engineer'
。name: fullName
。上一篇:js 对象解构
下一篇:js 转义符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站