2 回答

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
使用以下代碼更改localStorage代碼。問題是您將每次forEach迭代中的所有產(chǎn)品推送到本地存儲(chǔ)。
嘗試下面的代碼。
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貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
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));
}
這解決了重復(fù)問題,但在添加現(xiàn)有產(chǎn)品時(shí)仍然存在數(shù)量為空的問題。
- 2 回答
- 0 關(guān)注
- 162 瀏覽
添加回答
舉報(bào)