2 回答
TA贡献2065条经验 获得超13个赞
使用以下代码更改localStorage代码。问题是您将每次forEach迭代中的所有产品推送到本地存储。
尝试下面的代码。
if (products.length != 0) {
let isExists = products.some(shoe => shoe.name === newShoe.name);
if (!isExists) {
products.push(newShoe);
} else {
products = products.map(shoe => {
if (shoe.name == newShoe.name && !isNaN(newShoe.quantity)) {
shoe.quantity += newShoe.quantity;
return shoe;
}
return shoe;
});
}
localStorage.setItem("products", JSON.stringify(products));
} else {
products.push(newShoe);
localStorage.setItem("products", JSON.stringify(products));
}
TA贡献1111条经验 获得超0个赞
if (products.length != 0) {
for (let index = 0; index < products.length; index++) {
if (products[index].name == newShoe.name) {
products[index].quantity += newShoe.quantity;
localStorage.setItem("products", JSON.stringify(products));
break;
} else{
products.push(newShoe);
localStorage.setItem("products", JSON.stringify(products));
break;
}
}
} else {
products.push(newShoe);
localStorage.setItem("products", JSON.stringify(products));
}
这解决了重复问题,但在添加现有产品时仍然存在数量为空的问题。
- 2 回答
- 0 关注
- 119 浏览
添加回答
举报