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);
}
添加回答
舉報