【问题标题】:Determine whether an array contains a value and update or create it确定数组是否包含值并更新或创建它
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 我不知道当我更新 find 返回的对象时,更改会反映在数组中的等效项中。谢谢!!!
  • @klferreira -- 因为JS返回的是对item的引用,所以可以原地修改。
【解决方案2】:

更有效的方法是使用适当的数据结构 (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) 查找。

【讨论】:

  • 非常有趣。我一直将数组用于此类任务,但感觉不是正确的方法......一定会尝试Map
【解决方案3】:

试试看

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;

【讨论】:

  • 这如何满足 TO (@kiferreira) 的要求? O.o 如果有一个具有相同 id 的项目(仅用于获取其“类型”),一个新项目将被推送到数组/购物车中。否则什么都不做。而这一切都与一个误用的三元运算符...
  • typeof ( this.cart.items.find( a => { return a.id === item.id ? ( a.amount += item.amount, true ) : false; } ) ) !== '对象' ? this.cart.items.push(item) : undefined;
  • 为什么你认为这是误用了三元运算符?我不清楚。请解释一下。我想知道你@Andreas
猜你喜欢
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多