解构赋值

解构赋值是一种表达式,允许您使用数组或对象,将可迭代对象的值或属性分配给变量。解构赋值能让我们用更简短的语法进行多个变量的赋值,大大的减少了代码量。解构表达式有两种: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)//1,2,3
常用方法…
//忽略数组中某些值
let [a, , b] = [1, 2, 3];
console.log(a,b);//1,3
//使用展开语法
let [a, ...b] = [1, 2, 3, 4, 5, 6];
console.log(a);//1
console.log(b);//2,3,4,5,6
//跳过数组中的部分值
let [a, , ,...b] = [1, 2, 3, 4, 5, 6];
console.log(a);//1
console.log(b);	//4,5,6
//默认参数值
let [a, b, c = 3] = [1, 2];
console.log(c); // "3”
//嵌套数组
let [a, b, [c, d]] = [1, 2, [3, 4]]
//作为函数参数
function fun([a, b, c = 3]) {
    console.log(a, b, c); // "1 2 3"
}
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)//sutu,23
常用方法
//默认参数值
let {a, b, c = 3} = {a: "1", b: "2"};
console.log(c); // "3”
//在解构对象时变量名支持表达式计算
let {["first"+"Name"]: x} = { firstName: "sutu" };
console.log(x); //"sutu”
//嵌套对象
let {name, otherInfo: {age}} = {name: "sutu", otherInfo: {age:23}};
console.log(name, age); //sutu 23
//作为函数参数
function fun({name = 'sutu', age = 23, profession ="Designer"} = {}){
    console.log(name, age, profession); // "John 23 Designer"
}
fun({name: "John", age: 23});
其他
//获取字符串的长度
var {length}='sutu';
console.log(length);//4
//拆分字符串
var [a,b,c,d]='贾赫最帅';
console.log(a,b,c,d) // 输出:贾 赫 最 帅
//交换变量
let x = 1;
let y = 2;
[x, y] = [y, x];
//遍历Map结构
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 '../../../'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值