ES6个人学习整理(三)——解构赋值

解构赋值

ES6允许按照一定的模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
如果解构不成功,就会赋值undefined

数组

解构时按顺序排列
let [a, b, c] = [1, 2, 3];
// a = > 1; b => 2; c => 3;

let [a, [b, c], d] = [1, [2, 3], 4];
// a => 1; b => 2; c => 3; d => undefined;

// 当等号左边变量少于等号右边值时(包括变量缺省和变量个数不足), 仍可解构成功,成为不完全解构
let [a, , c] = [1, 2, 3];
// a => 1; c => 3;

// 多余参数的解构
let [a, b, ...c] = [1, 2, 3, 4, 5];
// a => 1; b => 2; c => [3, 4, 5];

// 解构不成功的情况
let [a] = [];
// a => undefined;
let [a, b] = [1]
// a => 1; b => undefined;

// 当等号右边不是数组或类数组(即可遍历的结构) 将会报错
let [a] = 1;
let [a] = false;
let [a] = NaN;
let [a] = undefined;
let [a] = null;
let [a] = {};
// TypeError: Invalid attempt to destruture non-iteable instance

对象

解构时无次序,属性名必须相同
let {a, b} = {a: 1, b: 2}
// a => 1; b => 2;

let {a, b, c} = {a: 1, c: 2, d: 3}
// a => 1; b => undefined; c => 2; d => d is not defined

let {a: b} = {a: 1, b: 2}
// a => a is not defined; b => 2

字符串

相当于把字符串切割成一个数组,顺位取
let [a, b, c] = 'string';
//  a => s; b => t; c => r;
let [a, b, c] = '字符串也可以解构';
//  a => 字; b => 符; c => 串;
let [a, b, c] = '字符';
//  a => 字; b => 符; c => undefined;

函数参数

let a = [1, 2];
function log ([a, b, c]) {
    // 相当于 let [a, b, c] = [1, 2];
    console.log(a, b, c);
    // a => 1; b => 2; c => undefined;
}
log(a);

function alert({title = 'title', content = 'content',   button = 'button'}) {
    console.log(title, content, button);
}
alert({title: '123'})

默认值

解构赋值也允许使用默认值
let [a = 1] = [2];
let [a = 1] = [NaN];
let [a = 1] = [true];
let [a = 1] = ['string'];
let [a = 1] = [null];
let [a = 1] = [undefined];
// 以上几种情况只哟传入的值为undefined时,默认值才会生效
// null 和 NaN 并不等于 undefined

// 如果默认值为表达式,那这个表达式是惰性求职的
let [a = b()] = [1];
function b() {
    // 无输出结果
    console.log('验证是否为惰性求值');
}

let b = 1;
let [a = ++b] = ['string'];
// a => string, b => 2
let [a = ++b] = [undefined];
// a => 2, b => 2

用途

// 交换宾变量的值
let [x, y] = [1, 2];
// x => 1; y => 2;
[y, x] = [x, y];
// x => 2; y => 1;

// 从数组或者json中提取值
function params() {
    return [1, 2, 3];
}
let [a, b, c] = params();

let obj = {
    a: 1,
    b: 2, 
    c: 3
}
let {a, b, c} = obj;

// 函数参数的默认值
function alert({title = 'title', content = 'content',   button = 'button'}) {
    console.log(title, content, button);
}
alert({title: '123'});

// 导入模块的指定值
import {A, B} from './const'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值