解构赋值是 JavaScript 中的一种特性,允许从对象或数组中提取数据并将其赋值给变量
const { 属性名1, 属性名2 } = Object;
属性名1 和 属性名2 是你想要提取的对象属性的名称。对象 是包含这些属性的对象。
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name);
console.log(age);
const person = { name: 'John' };
const { name, age = 25 } = person;
console.log(name);
console.log(age);
const person = { firstName: 'John', lastName: 'Doe' };
const { firstName: fName, lastName: lName } = person;
console.log(fName);
console.log(lName);
const [元素1, 元素2] = Array;
元素1 和 元素2 是你想要提取的数组元素的位置。数组 是包含这些元素的数组。
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
console.log(firstColor);
console.log(secondColor);
const colors = ['red', 'green', 'blue'];
const [firstColor, , thirdColor] = colors;
console.log(firstColor);
console.log(thirdColor);
-
可以使用剩余运算符 (...) 来获取余下的元素,并将它们存储在一个新数组中:
const colors = ['red', 'green', 'blue'];
const [firstColor, ...remainingColors] = colors;
console.log(firstColor);
console.log(remainingColors);
-
可以在对象和数组上使用嵌套解构,以提取深层嵌套的数据。
-
示例
const person = {
name: 'John',
address: {
city: 'New York',
zip: '10001'
}
};
const { name, address: { city, zip } } = person;
console.log(name);
console.log(city);
console.log(zip);
const data = [1, [2, 3]];
const [first, [second, third]] = data;
console.log(first);
console.log(second);
console.log(third);
解构赋值的基本用法和语法。通过解构赋值,可以更轻松地访问和操作对象和数组的数据