我正在尝试将数字加在一起作为一个汇总值,这取决于要在我的结帐页面上显示为总计的项目。
我尝试过
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语句,由于这是我在领域: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到处都是。帮助任何人???
答案 0 :(得分:1)
类似的东西:
//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
}
}
?
答案 1 :(得分:0)
如果使用数组方法,则每个步骤都非常容易且易于阅读。 除了少数情况以外,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 );
答案 2 :(得分:0)
最好的方法是如上所述的@Nil。但是,如果您想要不循环的“不可迭代”版本,您可以这样做:
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
}
}