# ES6解构赋值

smallStone
``````一、数组解构赋值：
var a = 1;
var b = 2;
var c = 3;

var [a,b,c] = [1,2,3];
let [a,b,c] = new Set([1,2,3]);

let [foo,[[bar],[baz]]] = [1,[[2],[3]]];

foo //  1; bar // 2; baz // 3;

let [,,third] == ["foo","bar","baz"];

third // "baz";

tail // [2,3,4];

let [x, y, ...z] = ['a'];

x // "a";
y // undefined;
z // [];

var [foo] == [];  foo // undefined
var [bar,foo] == [1];  foo // undefined

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

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

var [foo = true] = []; foo // true
let [x, y='b'] = ['a']; //x = 'a'; y = 'b'
let [x, y='b'] = ['a',undefined]; //x = 'a'; y = 'b'
ES6内部使用（===）完全等于来判断一个位置是否有值，所以，如果一个数组成员不严格等于undefined，默认值不会生效。
var [x = 1] = [undefined]; x // 1
var [x = 1] = [null]; x // null

function f(){ return 'aaa'};
let [x = f()] = [1];
x // 1

var x;
if([1][0] === undefined){x =f()}else{x = [1][0]}

var {foo, bar} = {foo:"aaa", bar:"bbb"};
foo // "aaa"
bar // "bbb"
*对象的解构赋值与数组一个重要的不同。数组必须是按次序排列，变量取值由未知决定；

var {baz} = {bar:"aaa"} // baz = "undefined"

var {foo：baz} = {foo: "aaa", bar: "bbb"};  // baz = "aaa"
let和const不允许重新声明！

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

let {length : len} = "hello"; // len = 5

let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true

return  x+y;
}
[[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]
undefined会触发函数的默认值
[1,undefined,3].map((x = "yes")=>x) // [1,"yes",3]``````

164 声望
27 粉丝
0 条评论