您的位置:首页 > Web前端 > JavaScript

js-es6-变量的解构赋值

2017-10-03 23:00 543 查看
本质上就是一种匹配模式,只要等号两边的模式相同,那么左边的变量就可以 被赋予对应的值。

 结构赋值主要分为:

    1 数组的解构赋值
    2 对象的结构赋值

    3 基本类型的解构赋值

数组的结构赋值

let [a, b, c] = [1, 2, 3];
console.log(a, b, c);//1,2,3
let [a, [[b], c]] = [1, [[2], 3]];
console.log(a, b, c);  // 1, 2, 3

let [, , c] = [1, 2, 3];
console.log(c); // 3

let [x] = [];
console.log(x);  //undefine
let [y = 1] = [];
console.log(y); // 1


对象的解构赋值

let {a, b} = {b: 'bbb', a: 'aaa'};
console.log(a, b);//aaa bbb

let {a: b} = {a: 1};
console.log(b);//1


基本类型的解构赋值

let [a, b, c, d] = '1234';
console.log(a, b, c, d);

let {length: len} = 'hello';
console.log(len);//5
let {toString: ts} = 1;
let {toString: bs} = true;
console.log(ts === Number.prototype.toString);//true
console.log(bs === Boolean.prototype.toString);//true


注意null 和 undefined 不能进行解构赋值

let [a] = null;//会报错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: