前言

JavaScript ES6 新增解构赋值,可以快读从数组或对象中取出成员

  • 解构: 将对象或者数组中的某个成员取出来
  • 赋值: 取出来的成员按顺序赋值给变量

python里面的解构赋值

如果有python语法基础,可以回顾一下python里面的解构赋值

a, b, c = [1, 2, 3]
print(a) # 1
print(b) # 2
print(c) # 3

abc会分别得到list列表里面的1,2,3。

还有一种场景,我们在交互a和b变量值的时候,也会用到

a = "hello"
b = "world"
a, b = b, a
print(a) # "world"
print(b) # "hello"

以上的场景其实就用到了解构赋值

数组的解构赋值

使用中括号 [ ] 来进行解构数组, 需注意变量名称和数组的值一一对应

let [a, b, c] = ['hello', 'world', 'yoyo'];
console.log(a, b, c); // hello world yoyo

或者把数组设置为一个变量,再解构

aa = ['hello', 'world', 'yoyo'];
let [a, b, c] = aa;
console.log(a, b, c); // hello world yoyo

如果变量的个数,少于数组的个数,变量会按顺序赋值,不会报错

aa = ['hello', 'world', 'yoyo'];
let [a, b] = aa;
console.log(a); // hello
console.log(b); // world

如果变量个数大于数组的个数,多余的变量为undefined

aa = ['hello', 'world', 'yoyo'];
let [a, b, c, d] = aa;
console.log(a);
console.log(b);
console.log(c);
console.log(d); // undefined

在使用entries() 遍历Map 成员的时候也可以用到解构赋值,entries() 返回 Map 对象中键/值对的迭代器

// for... of 遍历取key, value
for(let item of m.entries()){
console.log(item[0], item[1]);
}

item 是一个数组[key, value],可以使用解构赋值分别给到变量key, value

// 解构赋值[key, value] = item
for(let [key, value] of m.entries()){
console.log(key, value);
}

对象的解构赋值

对象的解构用大括号{}

const person = {
name: 'yoyo',
age: 20,
address: () => {
return "上海市"
}
}
let {name, age, address} = person;
console.log(name); // yoyo
console.log(age); // 20
console.log(address()); // 上海市

分别输出对象的属性对应的值。