如果对象不在本地存储数组中,我想将它们添加到本地存储数组中,否则将对象的数量增加 1。这是我的功能:
function addToCart() {
let productsTable = localStorage.getItem("productList");
// Check if productsTable exists in local storage
if (productsTable === null){
// 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 not ==> add the object into the array
objetProduit.quantity ++;
productsTable.push(objetProduit);
}else if (productsTable.find(product => product.id == objetProduit.id)){
//if yes ==> just increase the value of the key quantity by 1
objetProduit.quantity ++;
}
}
// Encode the array.
productsTable = JSON.stringify(productsTable);
// Add the array back to LocalStorage.
localStorage.setItem("productList", productsTable);
objetcs 是以下类的实例:
class Appareil {
constructor(id,name,price,description,imageURL, quantity){
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.imageURL = imageURL;
this.quantity = quantity;
}
}
数组已初始化,但未在其中添加项目,也未修改数量。
MM们
相关分类