解构赋值是一种表达式,允许您使用数组或对象,将可迭代对象的值或属性分配给变量。解构赋值能让我们用更简短的语法进行多个变量的赋值,大大的减少了代码量。解构表达式有两种:array和object。
1)数组
E6之前,我们可以这种形式将数组的内容赋值给多个变量:
var Array = [1, 2, 3];
var a = Array[0];
var b = Array[1];
var c = Array[2];
ES6中,我们可以通过数组解构语法,在一行语句里完成上述操作。
let Array = [1, 2, 3];
let a, b, c;
[a, b, c] = myArray;
let [a, b, c] = [1, 2, 3];
console.log(a,b,c)
常用方法…
let [a, , b] = [1, 2, 3];
console.log(a,b);
let [a, ...b] = [1, 2, 3, 4, 5, 6];
console.log(a);
console.log(b);
let [a, , ,...b] = [1, 2, 3, 4, 5, 6];
console.log(a);
console.log(b);
let [a, b, c = 3] = [1, 2];
console.log(c);
let [a, b, [c, d]] = [1, 2, [3, 4]]
function fun([a, b, c = 3]) {
console.log(a, b, c);
}
fun([1, 2]);
1)对象
ES6之前我们可以这样把对象的属性赋值给多个变量
var object = {name : "sutu", age : 18};
var name = object.name;
var age = object.age;
在ES6里,我们可以使用对象解构表达式,在单行里给多个变量赋值
let object = {name : "sutu", age : 23};
let {name,age}=object
console.log(name,age)
常用方法
let {a, b, c = 3} = {a: "1", b: "2"};
console.log(c);
let {["first"+"Name"]: x} = { firstName: "sutu" };
console.log(x);
let {name, otherInfo: {age}} = {name: "sutu", otherInfo: {age:23}};
console.log(name, age);
function fun({name = 'sutu', age = 23, profession ="Designer"} = {}){
console.log(name, age, profession);
}
fun({name: "John", age: 23});
其他
var {length}='sutu';
console.log(length);
var [a,b,c,d]='贾赫最帅';
console.log(a,b,c,d)
let x = 1;
let y = 2;
[x, y] = [y, x];
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " : " + value);
}
import { fun1,fun2 } from '../../../'