解構(gòu)賦值語(yǔ)法是一種 Javascript 表達(dá)式,它使得將值從數(shù)組废睦,或?qū)傩詮膶?duì)象施符,提取到不同的變量中,成為可能慈迈。(MDN)
語(yǔ)法
const [a,b] = [1,2]
console.log(a) //1
console.log(b) //2
const[a,b,...rest] = [1,2,3,4,5,6]
conslog.log(a) //1
console.log(b) // 2
console.log(rest) // [3,4,5,6]
const ({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20
解構(gòu)數(shù)組
var foo = ["one", "two", "three"];
var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
默認(rèn)值
為了防止從數(shù)組中取出一個(gè)undefined的對(duì)象,可以在表達(dá)式的左邊數(shù)組中為任意對(duì)象預(yù)設(shè)默認(rèn)值
var a,b
[a=4,b=6] = [2]
console.log(a)//2
console.log(b) //6
交換變量
var a = 1,b=2;
[a,b] = [b,a]
console.log(a) //2
console.log(b) //1
解構(gòu)對(duì)象
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true