// 示例代码:JS 对象解构
// 定义一个对象
const person = {
name: 'Alice',
age: 25,
address: {
city: 'Beijing',
country: 'China'
}
};
// 基本解构
const { name, age } = person;
console.log(name); // 输出: Alice
console.log(age); // 输出: 25
// 解构并重命名
const { name: fullName, age: years } = person;
console.log(fullName); // 输出: Alice
console.log(years); // 输出: 25
// 解构嵌套对象
const { address: { city, country } } = person;
console.log(city); // 输出: Beijing
console.log(country); // 输出: China
// 设置默认值
const { hobby = 'reading' } = person;
console.log(hobby); // 输出: reading (因为 person 中没有 hobby 属性)
// 解构并提供默认对象
const { job = 'engineer' } = person || {};
console.log(job); // 输出: engineer (因为 person 中没有 job 属性)
undefined
或 null
时,可以通过提供默认对象来避免错误。上一篇:js 获取文件大小
下一篇:js 转义符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站