ES6(解构赋值)
2020-04-28 本文已影响0人
KATENGC
解构赋值,分为左右两种解构
- 数组解构赋值 左右两边都是数组
- 对象解构赋值 左右两边都是对象
- 字符串解构赋值 左边是数组,右边是字符串
- 布尔解构赋值(就是对象解构赋值)
- 函数解构赋值
- 数值解构赋值(就是对象解构赋值)
//数组解构赋值
{
//用let 声明三个变量
let a, b, rest;
//相当于a=1 b=2
[a, b] = [1, 2];
console.log(a, b);// 1 2
}
//数组解构赋值
{
let a, b, rest;
[a, b, ...rest] = [1, 2, 3, 4, 5, 6];
console.log(a, b, rest);// 1 2 [3,4,5,6]
}
//对象解构赋值
{
let a, b;
({a, b} = {a: 1, b: 2});
console.log(a, b);// 1 2
}
//数组解构赋值 默认值
{
let a, b, c, rest;
[a, b, c = 3] = [1, 2];
console.log(a, b, c);// 1 2 3
}
//数组解构赋值 若没有在解构上成功配对,那么变量相当于只声明未赋值
{
let a, b, c, rest;
[a, b, c] = [1, 2];
console.log(a, b, c);// 1 2 undefined
}
//利用解构赋值 实现变量交换
{
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);//2 1
}
{
function f() {
return [1, 2];
}
let a, b;
[a, b] = f();
console.log(a, b);//1 2
}
{
function f1() {
return [1, 2, 3, 4, 5];
}
let a, b, c;
[a, , , b] = f1();
console.log(a, b);//1 4
}
{
function f2() {
return [1, 2, 3, 4, 5];
}
let a, b, c;
[a, ...b] = f2();
console.log(a, b);//1 [2,3,4,5]
}
//对象解构赋值
{
let o = {p: 42, q: true};
let {p, q} = o;
console.log(p, q);//42 true
}
//对象解构赋值 默认值
{
let {a = 10, b = 5} = {a: 3};
//a默认值为10 b默认值为5,通过赋值,a的值被覆盖为3,b没有被覆盖
console.log(a, b);//3 5
}
//对象解构赋值 嵌套应用
{
let metaData = {
title: 'abc',
test: [{
title: 'test',
desc: 'description'
}]
};
let {title: esTitle, test: [{title: cnTitle}]} = metaData
console.log(esTitle, cnTitle);//abc test
}