【发布时间】:2018-07-01 21:41:46
【问题描述】:
我有一个对象 this.items,我正在运行 for in,然后使用 find 方法通过 id 获取所有产品。我正在尝试根据条件设置 salesTax 金额(如果 taxPercent > 0),但循环执行的次数超过了预期的次数,因此 taxPercent 大于要求。
total() {
let total = 0
let tax = []
let importDuty = .05
for (let productId in this.items) {
total += this.inventory.products.find(product => {
if (product.taxPercent > 0) {
tax.push(product.price * product.taxPercent)
}
return product.id == productId
}).price * this.items[productId]
}
tax = tax.reduce((a, b) => a + b, 0)
let importDutyToApply = total * importDuty
total = total + importDutyToApply + tax
let response = {
'total': total,
'tax': tax
}
return response
}
我想知道如何设置税收总额以适用于未将 taxPercent 设置为 0 的任何商品。因此,如果我有三件商品,其中一件需要对 100 美元征收 10% 的税,则总计应该是 10 美元。同样,如果我有许多物品,其中一些需要 10% 的税,而另一些则不需要,它只会为需要它的那些加起来。有什么想法吗?
【问题讨论】:
标签: javascript oop object find for-in-loop