Blogger Information
Blog 13
fans 1
comment 0
visits 9903
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js2 解构,访问器属性
大宇
Original
632 people have browsed it

解构

数组解构

一个正常的代码:

  1. let arr = [1, 2, 3];
  2. let a = arr[0];
  3. let b = arr[1];
  4. let c = arr[2];
  5. console.log(a, b, c);

数组解构:等号左边和等号右边需要一样

  1. let [a,b,c] = [1,2,3];
  2. console.log(a,b,c)

效果是一样的

  1. [a, b, c = "js"] = [1, 2];
  2. console.log(a, b, c);
  3. [a, b, ...c] = [1, 2, 3, 4, 5, 6];
  4. console.log(a, b, ...c);
  5. // 这样只会拿到第四个值
  6. [, , , a, ,] = [1, 2, 3, 4, 5, 6];
  7. console.log(a, b, ...c);
  8. // 交换值
  9. let a = 10,
  10. b = 20;
  11. console.log(a, b);
  12. [b, a] = [a, b];
  13. console.log(a, b);
对象解构

也是一句话 等号左边和右边是一样的

  1. let item = { id: 10, name: "手机" };
  2. let id = item.id;
  3. let name = item.name;
  4. console.log("id=%d, name = %s", id, name);
  5. ({id, name}) = ({id:10, name:"电脑"});
参数解构
  1. let sum = ([a,b]) => a+b;
  2. console.log(sum[30,50])

对象传参

  1. let getUser = ({name,email})=>[name,email];
  2. console.log(getUser({name:"xxxx",email:"admin@php.cn"}))

访问器属性

访问器属性 将一个方法伪装/包装成一个属性

  1. const product = {
  2. data: [
  3. { id: 100, name: "电脑", price: 5000, num: 5 },
  4. { id: 100, name: "手机", price: 4000, num: 15 },
  5. { id: 100, name: "相机", price: 15000, num: 35 },
  6. ],

get读取 也叫读操作

  1. get total(){
  2. return this.data.reduce((t,c)=>(t += c.price * c.num), 0);
  3. }

set 访问器属性的写操作

  1. set setPrice(price){
  2. this.data[1].price = price;
  3. }
  4. // 不想用方法,想以属性的方式来获取总金额
  5. console.log("总金额 = %d 元", product.total);
  6. product.setPrice = 8000;
  7. console.log(product.data[1].price);

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