Blogger Information
Blog 34
fans 0
comment 0
visits 18417
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0401作业-解构与访问器属性
千山暮雪
Original
405 people have browsed it

1. 数组,对象,传参的解构

解构赋值语法是一种 Javascript 表达式。通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。

  • 数组的解构
  1. // 完全解构
  2. let [a,b,c] = [1,2,3];
  3. console.log('a:%d,b:%d,c:%d',a,b,c);
  4. // 部分解构
  5. let [d,e] = [4,5,6];
  6. console.log('d:%d,e:%d',d,e);
  7. // 支持默认值与归并
  8. let [f,g,h=10] = [7,8]
  9. console.log('f:%d,g:%d,h:%d',f,g,h);
  10. let[i,j,...k] = [1,2,3,4,5,6,7,8,9]
  11. console.log('i:%d,j:%d,k:%o',i,j,k);
  • 对象的解构
    1. let obj = {
    2. name:'张三',
    3. gender:'男',
    4. email:'tp@php.cn'
    5. }
    6. let {name,gender,email}= obj;
    7. console.log('name:%s,gender:%s,email:%s',name,gender,email);
    8. // 如果对象没有声明,需要使用()转为表达式
    9. ({name2,gender2,email2} = {name2:'李四',gender2:'女',email2:'admin@qq.com'});
    10. console.log('name2:%s,gender2:%s,email2:%s',name2,gender2,email2);

    变量名要与对象属性名相同
    属性名与变量名不相同时无法获得赋值

    1. ({name2,gender2,email2} = {name:'李四',gender:'女',email:'admin@qq.com'});
    2. console.log('name2:%s,gender2:%s,email2:%s',name2,gender2,email2);

    一个属性从一个对象解构,并分配给一个不同名称的变量

    1. ({name:name2,gender:gender2,email:email2} = {name:'李四',gender:'女',email:'admin@qq.com'});
    2. console.log('name2:%s,gender2:%s,email2:%s',name2,gender2,email2);
  • 传参的解构
  1. function User({name,email}) {
  2. console.log('name:%s,email:%s', name,email);
  3. }
  4. User({name:'王五',email:'admin@php.cn'});

2. 访问器属性的get,set操作

通过set,get修饰,把访问器的方法变成属性调用
访问器

  1. let user = {
  2. data:{name},
  3. set name(v) {
  4. this.data.name = v;
  5. },
  6. get name() {
  7. return this.data.name;
  8. }
  9. }
  10. console.log(user.name);
  11. user.name = '张三';
  12. console.log(user.name);
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:解构其实并非新事物 其实很多编程语言中都有的,例如 php中的list, 所以,多了解几种编程语言是很有用的,不是吗?
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