javascript - Javascript - 如果对象不存在,则将其添加到数组中,否则增加数量
问题描述
如果对象不在本地存储数组中,我想将它们添加到本地存储数组中,否则将对象的数量增加 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;
}
}
数组已初始化,但未在其中添加项目,也未修改数量。
解决方案
避免以下检查条件:
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);
}
推荐阅读
- powershell - 管道与参数参数输入?
- javascript - JavaScript字典值递增在嵌套for循环中不起作用
- flutter - 在 null 上调用了“signIn”。谷歌登录问题 Flutter
- wso2is - Deployment.toml - java.lang.StackOverflowError
- oracle - 用于检索自定义消息而不是异常详细信息的 PLSQL 异常处理
- php - 我想在 Show_form () 中打印错误列表,但我不能
- javascript - javascript 对象转换成新的数组对象?
- amazon-web-services - Jenkins AWS Codedeploy:部署大于 5GB 的文件
- html - 从包装文本的末尾开始 div
- python - 尝试在 python 中使用 Selenium 在贝宝上单击继续按钮