推送到 for in Javascript 内的数组

Push to array inside a for in Javascript

我有一个对象 this.items,我在 运行 for in 上,然后使用 find 方法通过 id 获取所有产品。我正在尝试根据条件(如果 taxPercent > 0)设置 salesTax 金额,但循环经历的次数超过预期次数,因此 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% 的税,而另一些则不需要,那么它只会加到需要它的那些上。有什么想法吗?

您传递给 find 的函数被调用了很多次。您只想为其找到的产品加税,而不是为其在途中查看的所有产品加税。

const product = this.inventory.products.find( product => product.id == productId );
if (product.taxPercent > 0) {
    tax.push(product.price * product.taxPercent)
}
total += product.price * this.items[productId]