如何根据复选框汇总值

how to summarize values depending on checked box

我正在尝试将这些数字加在一起作为汇总值,具体取决于选中的项目在我的结帐页面上显示为总计。

我试过了

if ( this.products[0].selected === true ) {
this.summary = this.products[0].price
} else if ( this.products[0].selected === true, this.products[1].selected === true  ) {
this.summary = this.products[0].price + this.products[1].price 
} else {
this.summary = 0;
}

显然没有完整的声明,但到目前为止它甚至都没有用。

我有一个包含这个的对象数组

data: {
  summary: 0,
  products: [
    { name: 'Hemsida', price: 290, selected: false },
    { name: 'Copywriting', price: 190, selected: false },
    { name: 'Fotografering', price: 190, selected: false }
  ]
}

当我选中我的框时,它会将链接变为 !products[0].selected

我最近的一次尝试是使用 switch 语句,我可能完全毁了它,因为这是我在该领域的第一个 switch 语句:P

  priceSummary() {
    switch (
      (this.products[0].selected,
      this.products[1].selected,
      this.products[2].selected)
    ) {
      case (true, false, false):
        this.summary = this.products[0].price
        break
      case (true, true, false):
        this.summary = this.products[0].price + this.products[1].price
        break
      case (true, false, true):
        this.summary = this.products[0].price + this.products[2].price
        break
      case (false, false, true):
        this.summary = this.products[2].price
        break
      case (false, true, false):
        this.summary = this.products[1].price
        break
      case (false, false, false):
        this.summary = 0
        break
      case (true, true, true):
        this.summary =
          this.products[0].price +
          this.products[1].price +
          this.products[2].price
      default:
        this.summary = 0
    }

它做了一些事情,但它没有做它应该做的事情:P 到处都是。帮助任何人???

类似的东西:

//looping on products
this.product.forEach((prod) => {
 //checking if product is selected
 if(prod.selected === true){
  // if it's selected, adding its price to the sum
  this.summary += prod.price
 }
}

?

如果使用数组方法,每一步都非常简单易读。 除了少数极端情况外,switch 语句不应替代循环。

const model = {
  data: {
    summary: 0,
    products: [
      { name: 'Hemsida', price: 290, selected: true },
      { name: 'Copywriting', price: 190, selected: true },
      { name: 'Fotografering', price: 190, selected: false }
    ]
  }
};
// Create an array of only selected products.
const selected_products = model.data.products.filter( product => product.selected );
// Sum the prices of the selected products.
const price = selected_products.reduce(( sum, product ) => sum + product.price, 0 );

model.data.summary = price;

console.log( model.data.summary );

最好的办法就是@Nil上面说的。但是如果你想要 "non-iterable" 没有循环的版本,你可以这样做:

priceSummary() {
    this.summary = 0

    if(this.products[0].selected) {
        this.summary += this.products[0].price // same as this.summary = this.summary + this.products[0].price
    }

    if(this.products[1].selected) {
        this.summary += this.products[1].price
    }

    if(this.products[2].selected) {
        this.summary += this.products[2].price
    }
}