1 回答
TA贡献1886条经验 获得超2个赞
避免以下检查条件:
if(productsTable.find(product => product.id !== objetProduit.id))
因为它将返回数组中不匹配的第一个产品的索引,所以很可能会有很多产品不匹配
参考:
https ://developer.mozilla.org/en-US/docs/Web/ JavaScript/参考/Global_Objects/数组/查找
尝试:
function addToCart() {
let productsTable = localStorage.getItem("productList");
// Check if productsTable exists in local storage
if (!productsTable) {
// If not, initialize the array and add the current object
productsTable = [];
objetProduit.quantity++;
productsTable.push(objetProduit);
} else {
// If yes, decode the array.
productsTable = JSON.parse(productsTable);
// check if the object is already in the array
if (productsTable.find(product => product.id === objetProduit.id)) {
//if yes ==> just increase the value of the key quantity by 1
objetProduit.quantity++;
for (var i = 0; i < productsTable.length; i++) {
if (objetProduit.id === productsTable[i].id) { //look for match with id
productsTable[i].quantity++; //add
break; //exit loop
}
}
} else {
//if not ==> add the object into the array
objetProduit.quantity++;
productsTable.push(objetProduit);
}
}
// Encode the array.
productsTable = JSON.stringify(productsTable);
// Add the array back to LocalStorage.
localStorage.setItem("productList", productsTable);
}
添加回答
举报