Blogger Information
Blog 25
fans 0
comment 0
visits 13654
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示对象与数组的解构赋值,及对象的访问器属性
安超
Original
321 people have browsed it

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
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:代码的执行内容可以直接使用截图
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!