【发布时间】:2018-03-26 15:14:10
【问题描述】:
所以我在 Javascript 中有这个 Cart 对象...我想做的是检查给定购物车中是否存在商品。
- 如果存在,请更新其数量。
- 如果没有,则将其推送到 items 数组。
我是这样做的
let item = {id: this.id, name: this.name, price: this.price, amount: this.amount}
let hasItem = false;
this.cart.items.forEach(element => {
if (element.id === item.id) {
element.amount += item.amount
hasItem = true;
}
})
if (!hasItem) {
this.cart.items.push(item);
}
它工作正常,但我想知道是否有更快、更有效的方法来做到这一点……你有什么建议?
【问题讨论】:
-
如果您知道只有一个具有该 id 的项目,您可以在找到后跳过其余的项目。看看
findMethod。但是不,您无法使用数组提高效率(除非您对其进行排序)。 -
@Archer 呃,不是吗?
-
@georg 为什么是
Map? -
@klferreira:发布在下面
标签: javascript logic