博客列表 >实例演示对象与数组的解构赋值,及对象的访问器属性

实例演示对象与数组的解构赋值,及对象的访问器属性

安超
安超原创
2022年11月04日 19:03:18324浏览

1.数组的解构赋值

  1. let arr_1 = [1,3];
  2. let [x,y] = arr_1;
  3. console.log(`x is: ${x} and y is: ${y}`);
  4. // 用数组交换变量
  5. [y,x ] = [x,y];
  6. console.log(` 交换后的x,y为:${x} adn ${y}`);
  7. console.log("------------------------");

2.对象解构 变量名需要和对象的属性名一致

  1. console.log("对象解构");
  2. let obj = {one:"oneobj",two:"twoobj",three:"threeobj"};
  3. let {one,two,three} = obj;
  4. console.log(one);
  5. // 对象的值改变,必须在整条语句上加(),
  6. obj = {one:"oneobj_1",two:"twoobj_2",three:"threeobj_2"};
  7. ({one,two,three} = obj);
  8. console.log(one);
  9. console.log("--------------------------------");

2.1 解构对象的用处一:克隆对象

  1. console.log("解构对象的用处一:克隆对象");
  2. let obj_1 = {one:"oneobj",two:"twoobj",three:"threeobj"};
  3. let {...objCopy} = obj_1;
  4. console.log(objCopy);
  5. console.log("-----------------------------------");

2.2 解构对象的用处二:简化传参

  1. let sum = function({name,address}){ //直接应用对象的属性
  2. return `${name} and ${address}`;
  3. }
  4. let user = {name:"jiao",address:"beijng"};
  5. console.log(sum(user));

3.访问器属性,可以将方法伪装成属性

  1. console.log("访问器器的一个显著特点是将方法伪装成属性,可以像调用属性一样调用方法");
  2. let obj_2 = {
  3. name:"jiao",
  4. address:"beijing",
  5. get info(){
  6. return {name:this.name,address:this.address};
  7. },
  8. set info({name,address}){
  9. this.name = name;
  10. this.address = address;
  11. }
  12. }
  13. let name = obj_2.info.name;
  14. let address = obj_2.info.address;
  15. console.log(name +" and "+ address);
  16. obj_2.info={name:"wang",address:"hefei"};
  17. name = obj_2.info.name;
  18. address = obj_2.info.address;
  19. console.log(name);
  20. console.log(address);

4.上述代码执行后,结果见如下:

  1. x is: 1 and y is: 3
  2. 交换后的x,y为:3 adn 1
  3. ------------------------
  4. 对象解构
  5. oneobj
  6. oneobj_1
  7. --------------------------------
  8. 解构对象的用处一:克隆对象
  9. { one: 'oneobj', two: 'twoobj', three: 'threeobj' }
  10. -----------------------------------
  11. jiao and beijng
  12. 访问器器的一个显著特点是将方法伪装成属性,可以像调用属性一样调用方法
  13. jiao and beijing
  14. wang
  15. hefei
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议