ES6 变量的结构赋值

1.数组的解构赋值

  a.基本用法:(‘模糊匹配’)

let [a, b, c] = [1, 2, 3];
a//1
b//2
c//3

b.嵌套数组结构例子:

let [x, , y] = [1, 2, 3];
x // 1
y // 3
------------------------------------------------
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
------------------------------------------------
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

如果结构不成功,变量的指就等于undefined

let [foo] = [];
let [bar, foo] = [1];

c.不完全解构:只匹配能匹配到的

let [x, y] = [1, 2, 3];
x // 1
y // 2

let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

注:解构右边不是数组,将会报错(或者严格地说,不是可遍历的结构,参见《Iterator》一章)

2.默认值

解构赋值允许指定默认值。

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
let [x = 1] = [null];
x//null

注:ES6 内部使用严格相等运算符(===),只有当一个数组成员严格等于undefined,默认值才会生效,其中null不严格等于undefined

3.对象的解构赋值

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

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

注:多次解构

const node = {
  loc: {
    start: {
      line: 1,
      column: 5
    }
  }
};

let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // Object {start: Object}
start // Object {line: 1, column: 5}

a.将一个已经声明的变量用于解构赋值,必须非常小心

// 错误的写法
let x;
{x} = {x: 1};
// SyntaxError: syntax error

  上面代码的写法会报错,因为 JavaScript 引擎会将{x}理解成一个代码块,从而发生语法错误。只有不将大括号写在行首,避免 JavaScript 将其解释为代码块,才能解决这个问题。

// 正确的写法
let x;
({x} = {x: 1});

  由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构

let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3

4.字符串的解构赋值

字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。

规则:解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefinednull无法转为对象,所以对它们进行解构赋值,都会报错。

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

原文地址:https://www.cnblogs.com/nailc/p/9208288.html