定义:
解构赋值就是从目标对象或数组中提取自己想要的变量。最常用的场景是:element-ui,vant-ui按需引入,请求接口返回数据,提取想要数据。
语法:
var a, b, rest;
[a, b] = [10, 20];
console.log(a);
console.log(b);
({ a, b } = { a: 10, b: 20 });
console.log(a);
console.log(b);
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a);
console.log(b);
console.log(rest);
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a);
console.log(b);
console.log(rest);
function f() {
return [1, 2];
}
var a, b;
[a, b] = f();
console.log(a);
console.log(b);
更多应用场景
- 默认值
var a, b;
[a=5, b=7] = [1];
console.log(a);
console.log(b);
- 交换变量
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a);
console.log(b);
- 忽略你不感兴趣的返回值
function f() {
return [1, 2, 3];
}
var [a, , b] = f();
console.log(a);
console.log(b);
- 将剩余数组赋值给一个变量
当解构一个数组时,可以使用剩余模式,将数组剩余部分赋值给一个变量。
var [a, ...b] = [1, 2, 3];
console.log(a);
console.log(b);
- 给新的变量名赋值
可以从一个对象中提取变量并赋值给和对象属性名不同的新的变量名。
var o = {p: 42, q: true};
var {p: foo, q: bar} = o;
console.log(foo);
console.log(bar);
- For of 迭代和解构
var people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith'
},
age: 35
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
},
age: 25
}
];
for (var {name: n, family: {father: f}} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
|