【问题标题】:Push to array inside a for in Javascript在Javascript中推送到for中的数组
【发布时间】: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


    【解决方案1】:

    你传递给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]
    

    【讨论】:

    • 另外,我想你想把税乘以 this.items[productId]?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2011-07-07
    • 2021-08-14
    相关资源
    最近更新 更多