您的位置:首页 > 其它

ES6--变量的解构赋值

2017-09-24 20:57 405 查看

1.基本概念

解构赋值:本质上就是一种匹配模式,只要等号两边的模式相同,那么左边的变量就可以 被赋予对应的值。

* 结构赋值主要分为:

* 1 数组的解构赋值

* 2 对象的结构赋值

* 3 基本类型的解构赋值

举个栗子

let a = 1;
let b = 2;
let c = 3;


等价于

let [a, b, c] = [1, 2, 3];


变量的解构赋值分为三种,以下一一介绍

2.三种解构赋值

1) 数组的解构赋值

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);  // let x; undefined此处解构不成功


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


2) 对象的解构赋值

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


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


3) 基本类型的解构赋值

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


let {length: len} = 'miaov';
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;//报错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: