ES6笔记之解构赋值

一、数组解构赋值

let [x, y] = [1, 2];    // x=1; y=2
let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError: y is not defined

二、对象解构赋值

对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };
baz // unefind

三、字符串的解构赋值

const [a, ...b] = 'hello';
a // "h"
b // "elle"

四、用途:
1、变量交换
2、提取对象的属性
3、遍历Map解构

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

map是Map的实例对象,此时的解构赋值却用了[]符号而非{},原因在于Set 结构for … of遍历时,返回的是一个值,而 Map 结构for … of遍历时,返回的是一个数组,该数组的两个成员分别为当前 Map 成员的键名和键值。

注:for…of 仅可用于拥有iterator接口的数据结构

猜你喜欢

转载自blog.csdn.net/qq_36470086/article/details/82393147