解构不仅可以用于数组,也可以用于对象。对象解构赋值与数组解构赋值有什么异同呢?
(1)对象的属性没有次序,变量必须与属性同名,才能渠道正确的值;
(2)指定默认值时,对象默认值生效的条件是:对象的属性值严格等于undefined;
(3)对象的解构赋值。可以很方便将现有对象方法赋值到某个变量。
案例2-1:对象的解构赋值.html
<script type="text/traceur">
var {name,age} = {name:"Zhangsan",age:12};
console.log(name); //Zhangsan
console.log(age); //12
</script>
性质1:对象解构赋值不按照顺序案例2-2:对象解构赋值不按照顺序.html
<script type="text/traceur">
var {name,age,id} = {id:"007",name:"Zhangsan",age:12};
console.log(name); //Zhangsan
console.log(age); //12
console.log(id); //007
//若“007”不加双引号,即可以显示为7,
</script>
解析:(1)当“id:007”时,此时的id为数值类型,会console.log(id);为“7”;
(2)当“id:"007"”时,此时的id为字符串类型,会console.log(id);为“007”。
案例2-3:变量和属性名不一致.html
<script type="text/traceur">
var {person_name,person_age,person_id} = {id:"007",name:"Zhangsan",age:12};
console.log(person_name); //undefined
console.log(person_age); //undefined
console.log(person_id); //undefined
</script>
解析:上述案例中,person_name与name表明变量与属性名并不匹配,会显示“错误”。
解决办法:将person_name赋值给name即可
<script type="text/traceur">
var {name:person_name,age:person_age,id:person_id} = {id:"007",name:"Zhangsan",age:12};
console.log(person_name); //Zhangsan
console.log(person_age); //12
console.log(person_id); //007
let object = {first:"Hello",last:"world"};
let {first:firstName,last:lastName} = object;
console.log(firstName); //Hello
console.log(lastName); //world
</script>
案例2-4:对象解构默认值.html
<script type="text/traceur">
var { x=3 } ={};
console.log(x); //3
var { x,y = 5} = {x:1};
console.log(x); //1
console.log(y); //5
var {message:msg="You are a person!"};
console.log(msg); //You are a person!
</script>
案例2-5:对象解构默认值条件.html
<script type="text/traceur">
var {x=3} = {x : undefined};
console.log(x); //3
var {y=3} = {y : null};
console.log(y); //null
</script>
总结:默认值条件:对象的属性值严格等于undefined
案例2-6:已声明变量的解构赋值.html
<script type="text/traceur">
var x;
({x} = {x:1});
console.log(x); //1
</script>
案例2-7:现有对象的方法.html
<script type="text/traceur">
console.log(Math.sin(Math.PI/6)); //0.499999
let {sin,cos,tan,log} = Math;
console.log(sin(Math.PI/6)); //0.499999
</script>