gpt4 book ai didi

javascript - 在 Javascript 中推送到 for 内的数组

转载 作者:行者123 更新时间:2023-11-30 14:31:17 25 4
gpt4 key购买 nike

我有一个对象 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]

关于javascript - 在 Javascript 中推送到 for 内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com