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

================================================================

经典案列
let [a,b] = [1,2];
console.log(a,b);//1,2
[a,b] = [b,a];
console.log(a,b);//2,1

//传统写法 ============================================
let a = 1;
let b = 2;
console.log(a,b);//1,2
let c;
c=a;
a=b;
b=c;
console.log(a,b);//2,1

tips解构赋值
1、两边数据解构格式必须一致
2、声明和赋值 一句话里完成
3、右边不能为空!否则会会报错

posted on 2019-02-05 14:04  安度因路飞  阅读(86)  评论(0编辑  收藏  举报

导航