2-变量的解构赋值

let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]]; -->  foo // 1  bar // 2  baz // 3
let [ , , third] = ["foo", "bar", "baz"]; --> third // "baz"
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 // []
let [x, y, z] = new Set(['a', 'b', 'c']);   --> x // "a"
***如果等号的右边不是数组(或者严格地说,不是可遍历的结构,参见《Iterator》一章),那么将会报错,只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值

  可以设置默认值

let [x, y = 'b'] = ['a']; // x='a', y='b'
let { foo, bar } = { foo: 'aaa', bar: 'bbb' }; --> foo // "aaa"  bar // "bbb"

数组的元素是按次序排列的,变量的取值由它的位置决定;对象的属性没有次序,变量必须与属性同名,才能取到正确的值

let { bar, foo } = { foo: 'aaa', bar: 'bbb' }; --> foo // "aaa"  bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' }; --> baz // undefined
如果变量名与属性名不一致,必须写成下面这样
let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; --> baz // "aaa"
对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。
let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; --> baz // "aaa"
foo // error: foo is not defined
对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。
let { log, sin, cos } = Math;

  可以设置默认值 

var {x, y = 5} = {x: 1}; --> x // 1   y // 5

三、字符串的解构赋值

字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象
const [a, b, c, d, e] = 'hello'; --> a // "h"  b // "e"  c // "l"  d // "l"  e // "o

类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值
let {length : len} = 'hello'; --> len // 5

四、数值和布尔值的解构赋值

解构赋值时,如果等号右边是数值和布尔值,则会先转为对象
let {toString: s} = 123; --> s === Number.prototype.toString // true

let {toString: s} = true; --> s === Boolean.prototype.toString // true

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

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError

五、函数参数的解构赋值

function add([x, y]){
  return x + y;
}
add([1, 2]); --> // 3
[[1, 2], [3, 4]].map(([a, b]) => a + b); --> // [ 3, 7 ]

  可以设置默认值

function move({x = 0, y = 0} = {}) {
  return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]

下面代码是为函数move的参数指定默认值,而不是为变量x和y指定默认值,所以会得到与前一种写法不同的结果。

function move({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]

六、圆括号问题

好烦呀,下一遍再看,,总是耐不住性子

猜你喜欢

转载自www.cnblogs.com/slightFly/p/11871096.html