为了账号安全,请及时绑定邮箱和手机立即绑定

我想声明类中对象的值,并且仅在Im声明新类时调用键。我该怎么办?

我想声明类中对象的值,并且仅在Im声明新类时调用键。我该怎么办?

UYOU 2022-09-23 16:16:19

这就是我到目前为止所做的。


class PriceCalc {

  constructor(Obj) {

    this.parts = Object.keys(Obj);

    this.cost =

      "$" +

      Object.values(Obj)

        .reduce((a, b) => a + b, 0)

        .toFixed(2);

    this.retail =

      "$" +

      (

        Object.values(Obj).reduce((a, b) => a + b, 0) +

        Object.values(Obj).reduce((a, b) => a + b, 0) * 1.75

      ).toFixed(2);

    this.quote = qt + this.retail;

  }

}

var total = new PriceCalc({

  Motherboard: 520.99,

  RAM: 250.4,

  SSD: 500.8,

  HDD: 400.66,

  Case: 375.5,

  Monitor: 600.75,

  Keyboard: 100.99,

  Mouse: 25.5

});

console.log(total.parts);

console.log(total.cost);

console.log(total.retail);

console.log(total.quote);

Id想要实现的是将值声明在类中,然后只调用类似的东西


var total = new PriceCalc({Motherboard, RAM, SSD, HDD});

并返回指定部件的组合值,在本例中为 $1,672.85,对于此.cost


查看完整描述

1 回答

?
森林海

TA贡献1646条经验 获得超1个赞

  1. 将默认值放入类属性。

  2. 传递要获取的属性字符串。

  3. 用于获取对象属性this[b]

  4. 确保你把数字而不是字符串相加:会给你字符串串联而不是算术运算。qt + this.quote

class PriceCalc {

  Motherboard = 520.99;

  RAM = 250.40;

  SSD = 500.80;

  HDD = 400.66;

  Case = 375.50;

  Monitor = 600.75;

  Keyboard = 100.99;

  Mouse = 25.50;

  

  parts = []

  cost = '$0'

  retail = '$0'

  quote = '0'


  constructor(Obj) {

    this.parts = Obj.join(',');

    this.cost = "$" + (Obj.reduce((a, b) => a + this[b], 0).toFixed(2));

    this.retail = "$" + ((Obj.reduce((a, b) => a + this[b], 0) + (Obj.reduce((a, b) => a + this[b], 0) * 1.75)).toFixed(2));

    //this.quote = qt + this.retail;

  }

}


var total = new PriceCalc([

  'Motherboard',

  'RAM',

  'SSD',

  'HDD'

]);


console.log(total.parts)

console.log(total.cost)

console.log(total.retail)

console.log(total.quote)


查看完整回答
反对 回复 2022-09-23
  • 1 回答
  • 0 关注
  • 7 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信