es6--(二)变量的解构赋值

1.数组的解构赋值

 //数组解析
 let [a,b,c] = [1,2,3]; //a=1;b=2;c=3
 //嵌套数组
 let [a,[b,c]] = [1,[2,3]];//a=1;b=2;c=3
 //空缺变量
  let [a,,c] = [1,2,3]; //a=1,c=3
 //...
 let [a,...other] = [1,2,3];//a=1;other=[2,3]
 //多余变量
 let [a,b,c] = [1,2];//a=1,b=2,c=undefined
 let [a,b,...c]=[1];//a=1,b=undefined,c=[]
//默认值
let [a,b,c=3] = [1,2]; //a=1'b=2;c=3

2.对象解构

//对象解构
let {id, name} = {id:"1",name:"bella"}; //id = 1;name="bella"
//嵌套对象(p是模式,不会被赋值)
let {p:[id,{name}]} = {p:[1:{name:"bella"}]};//x="1",y="bella"
//指定默认值
let { id = 1} = {}; //id = 1
let {id:name = "bella"}; // name = "bella"

3.字符串解构

let [a,b,c] = "abc"; //a="a";b="b";c="c"
let { length : len } = "abc";//len = 5

4.数值和布尔解构

//如果等号右边是number和boolean,则先会转换成对象
let {toString : s} = 1;
s === Number.prototype.toString //true

let {toStrings: s} = true;
s === Boolean.prototype.toString //true

5.函数参数解构

function add([x,y]){
     return x + y;       
}

add([1,2]); //3

//默认值
function add([x=0,y=0]){
    return x + y;
}
add(); //0

  

  

 

  

原文地址:https://www.cnblogs.com/thonrt/p/6227059.html