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

时间:2018-03-26 15:14:10

标签: javascript logic

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

  • 如果有,请更新其金额。
  • 如果没有,请将其推送到items数组。

我这样做了

SubList

它工作正常,但我想知道是否有更快,更有效的方法这样做......你会建议什么?

3 个答案:

答案 0 :(得分:2)

使用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;
}

答案 1 :(得分:1)

更有效的方法是使用适当的数据结构(Map)而不是数组,例如:



let basket = new Map();

function add(product) {
    if(basket.has(product.id))
        basket.get(product.id).amount += product.amount;
    else
        basket.set(product.id, {...product});
}

add({id:1, name: 'bread', amount:1});
add({id:2, name: 'butter', amount:2});
add({id:1, name: 'bread', amount:2});
add({id:1, name: 'bread', amount:1});

console.log([...basket.values()])




这样,您就可以通过产品ID保证O(1)查找。

答案 2 :(得分:0)

试试吧

let item = { id: this.id, name: this.name, price: this.price, amount: this.amount };

typeof ( this.cart.items.find( a => { return a.id === item.id ? ( a.amount += item.amount, true ) : false; } ) ) !== 'object' ? this.cart.items.push( item ) : undefined;
相关问题