解构赋值语法是一种 Javascript 表达式,它使得将值从数组,或属性从对象,提取到不同的变量中,成为可能。(MDN)
语法
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
解构数组
var foo = ["one", "two", "three"];
var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
默认值
为了防止从数组中取出一个undefined的对象,可以在表达式的左边数组中为任意对象预设默认值
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
解构对象
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
网友评论