1.数组的解构赋值
let arr_1 = [1,3];
let [x,y] = arr_1;
console.log(`x is: ${x} and y is: ${y}`);
// 用数组交换变量
[y,x ] = [x,y];
console.log(` 交换后的x,y为:${x} adn ${y}`);
console.log("------------------------");
2.对象解构 变量名需要和对象的属性名一致
console.log("对象解构");
let obj = {one:"oneobj",two:"twoobj",three:"threeobj"};
let {one,two,three} = obj;
console.log(one);
// 对象的值改变,必须在整条语句上加(),
obj = {one:"oneobj_1",two:"twoobj_2",three:"threeobj_2"};
({one,two,three} = obj);
console.log(one);
console.log("--------------------------------");
2.1 解构对象的用处一:克隆对象
console.log("解构对象的用处一:克隆对象");
let obj_1 = {one:"oneobj",two:"twoobj",three:"threeobj"};
let {...objCopy} = obj_1;
console.log(objCopy);
console.log("-----------------------------------");
2.2 解构对象的用处二:简化传参
let sum = function({name,address}){ //直接应用对象的属性
return `${name} and ${address}`;
}
let user = {name:"jiao",address:"beijng"};
console.log(sum(user));
3.访问器属性,可以将方法伪装成属性
console.log("访问器器的一个显著特点是将方法伪装成属性,可以像调用属性一样调用方法");
let obj_2 = {
name:"jiao",
address:"beijing",
get info(){
return {name:this.name,address:this.address};
},
set info({name,address}){
this.name = name;
this.address = address;
}
}
let name = obj_2.info.name;
let address = obj_2.info.address;
console.log(name +" and "+ address);
obj_2.info={name:"wang",address:"hefei"};
name = obj_2.info.name;
address = obj_2.info.address;
console.log(name);
console.log(address);
4.上述代码执行后,结果见如下:
x is: 1 and y is: 3
交换后的x,y为:3 adn 1
------------------------
对象解构
oneobj
oneobj_1
--------------------------------
解构对象的用处一:克隆对象
{ one: 'oneobj', two: 'twoobj', three: 'threeobj' }
-----------------------------------
jiao and beijng
访问器器的一个显著特点是将方法伪装成属性,可以像调用属性一样调用方法
jiao and beijing
wang
hefei