推荐答案
// www.javascriptcn.com code example
// 数组解构赋值
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
// 对象解构赋值
const { name, age } = { name: 'Alice', age: 25 };
console.log(name); // Alice
console.log(age); // 25
// 默认值
const [x = 10, y = 20] = [1];
console.log(x); // 1
console.log(y); // 20
// 嵌套解构
const { info: { title, year } } = { info: { title: 'JavaScript', year: 2023 } };
console.log(title); // JavaScript
console.log(year); // 2023本题详细解读
数组解构赋值
数组解构赋值允许你从数组中提取值,并将它们赋值给变量。语法如下:
const [a, b] = [1, 2];
在这个例子中,a 被赋值为 1,b 被赋值为 2。
对象解构赋值
对象解构赋值允许你从对象中提取属性,并将它们赋值给变量。语法如下:
const { name, age } = { name: 'Alice', age: 25 };在这个例子中,name 被赋值为 'Alice',age 被赋值为 25。
默认值
解构赋值允许你为变量设置默认值,当解构的值是 undefined 时,将使用默认值。语法如下:
const [x = 10, y = 20] = [1];
在这个例子中,x 被赋值为 1,而 y 由于没有对应的值,因此使用默认值 20。
嵌套解构
解构赋值还可以用于嵌套的对象或数组。语法如下:
const { info: { title, year } } = { info: { title: 'JavaScript', year: 2023 } };在这个例子中,title 被赋值为 'JavaScript',year 被赋值为 2023。
解构赋值是 JavaScript 中非常强大且常用的特性,能够简化代码并提高可读性。