ECMA6 001 解构赋值
Posted anduyinglufei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ECMA6 001 解构赋值相关的知识,希望对你有一定的参考价值。
传统数组赋值
let arr = new Array();
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
console.log(arr[0],arr[1],arr[2]); //1 2 3
每个都需要手写一次太麻烦!
//ES6数组解构
let [a,b,c] = [1,3,4];
console.log(a,b,c); // 1 3 4
==============================================================
//传统对象赋值
let ob = new Object();
ob.name = "zf";
ob.age = 18;
console.log(ob.name,ob.age);// zf 18
每个都需要手写一次太麻烦!
//ES6对象赋值
let {name,age} = {name:"zf",age:18};
console.log(name,age); // zf 18
注意 let 变量名 必须和 {对象里的属性名一致}
let {name:n,age:a} = {name:‘zf‘,age:[24,11]};
console.log(n,a); // zf [24,11]
//注意两边解构必须一致 let {} = {} 即 对象 = 对象
===============================================================
//混合赋值一
let [{name,age},[a,b],c] = [{name:‘zf‘,age:18},[2,3],‘zzz‘];
//混合赋值二
let {name,age:[a,b]} = {name:‘zf‘,age:[24,11]};
console.log(name,a,b); // zf 24 11
//混合赋值三
let {name,age} = {name:‘zf‘,age:[24,11]};
console.log(name,age); // zf [24,11]
//混合赋值四
let [a,b] = [[2,3],{name:‘zf‘,age:33}];
console.log(a,b); // [2, 3] {name: "zf", age: 33}
//混合赋值五
let [[a,b],{name:c,age:[d,e]}] = [[2,3],{name:‘zf‘,age:[5,7]}];
console.log(a,b,c,d,e) //2 3 "zf" 5 7
================================================================
tips解构赋值
1、两边数据解构格式必须一致
2、声明和赋值 一句话里完成
3、右边不能为空!否则会会报错
以上是关于ECMA6 001 解构赋值的主要内容,如果未能解决你的问题,请参考以下文章