gpt4 book ai didi

javascript - 确定数组是否包含值并更新或创建它

转载 作者:行者123 更新时间:2023-11-29 20:55:36 24 4
gpt4 key购买 nike

所以我在 Javascript 中有这个购物车对象...我想做的是检查给定购物车中是否存在商品。

  • 如果存在,请更新其数量。
  • 如果没有,将其推送到 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);
}

它工作正常,但我想知道是否有更快、更有效的方法...您有什么建议?

最佳答案

使用Array#find方法。最大的优点是,如果在数组中找到该项目,它就不会进一步遍历数组(forEach 会这样做,而且您无法阻止它这样做)。

let item = {id: this.id, name: this.name, price: this.price, amount: this.amount};
let listItem = this.cart.items.find(element => element.id === item.id)

if (!listItem) {
this.cart.items.push(item);
} else {
listItem.amount += item.amount;
}

关于javascript - 确定数组是否包含值并更新或创建它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49494875/

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