JavaScript 解构

解构赋值语法

解构赋值语法将对象属性解包到变量中:

let {firstName, lastName} = person;

它还可以解包数组和任何其他可迭代对象:

let [firstName, lastName] = person;

对象解构

Instance

// 创建一个对象
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Deconstruction
let {firstName, lastName} = person;

Try it yourself

属性的顺序无关紧要:

Instance

// 创建一个对象
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Deconstruction
let {lastName, firstName} = person;

Try it yourself

注意:

解构不是破坏性的。

解构不会更改原始对象。

对象默认值

对于可能缺失的属性,我们可以设置默认值:

Instance

// 创建一个对象
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Deconstruction
let {firstName, lastName, country = "US"} = person;

Try it yourself

对象属性别名

Instance

// 创建一个对象
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Deconstruction
let {lastName: name} = person;

Try it yourself

字符串解构

解构的一个用途是解包字符串字符。

Instance

// 创建一个字符串
let name = "W3Schools";
// Deconstruction
let [a1, a2, a3, a4, a5] = name;

Try it yourself

注意:

解构可以用于任何可迭代对象。

数组解构

我们可以将数组变量提取到自己的变量中:

Instance

// Create an array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Deconstruction
let [fruit1, fruit2] = fruits;

Try it yourself

跳过数组值

我们可以使用两个或更多逗号来跳过数组值:

Instance

// Create an array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Deconstruction
let [fruit1,,,fruit2] = fruits;

Try it yourself

数组位置值

我们可以从数组的特定索引位置提取值:

Instance

// Create an array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Deconstruction
let {[0]: fruit1, [1]: fruit2} = fruits;

Try it yourself

剩余属性

可以在解构语法末尾使用剩余属性。

Syntax na zai a iya gudanar da kawo kiyaye dukkanin tsawon kudirgi zuwa gidan guda na nau'i kudirgi:

Instance

// Create an array
const numbers = [10, 20, 30, 40, 50, 60, 70];
// Deconstruction
const [a, b, ...rest] = numbers;

Try it yourself

Deconstruct Map

Instance

// Create a Map
const fruits = new Map([
  ["apples", 500],
  ["bananas", 300],
  
]
// Deconstruction
let text = "";
for (const [key, value] of fruits) {
  text += key + " is " + value;
}

Try it yourself

Swap JavaScript variable

A za a iya amfani da assignment na deconstruction don kawo kiyaye tsaki na biyu:

Instance

let firstName = "Bill";
let lastName = "Gates";
// Deconstruction
[firstName, lastName] = [lastName, firstName];

Try it yourself