如果使用 TypeScript 的数组中已经存在键值,如何通过 onclick 增加键值?

How to increment the key value by onclick if already the key value present in the array using TypeScript?

这里我有 onclick 函数,它从 detailss 数组中获取 Product_idProduct_namePrice。我正在使用本地存储阵列愿望清单存储此值。

现在我被困在更新本地存储阵列愿望清单中的数量, 如果 productid 已经存在于本地存储中,我需要添加数量。

addToCart(Product_id){
    
    var name=[{
        Product_id:this.detailss[0].Product_id,
        Product_name:this.detailss[0].Product_name,
        Price:this.detailss[0].Price,
        Quantity:"",
        
    }];

var a = JSON.parse(localStorage.getItem('wishlist')) || [];
a.push(name);
localStorage.setItem('wishlist', JSON.stringify(a));
console.log(Product_id);

}



    

提前致谢。

  1. 从 localStorage 获取值并将其解析为对象

var myList = JSON.parse(localStorage.getItem('wishlist')) || [];

  1. 查找带有 Product_id
  2. 的产品

addQuantity(Product_id,passedQuantity) {

  let productIndex=myList.findIndex(eachProduct=> eachProduct.Product_id==Product_id);
  if(productIndex==-1)
  {
  //Product does not exist in the array
  }
  else
  {
  myList[productIndex].Quantity=passedQuantity;
  }
}
  1. 再次将数组字符串化并保存回 localStorage

localStorage.setItem('wishlist', JSON.stringify(myList));

仅在项目存在时添加金额的函数。

在此示例中,通过单击购物车内的 + 按钮添加金额:

addAmount(Product_id){
    let myArray = JSON.parse(localStorage.getItem('wishlist'));
        for(let i = 0; i < myArray.length; i++){
           if(Product_id == myArray[i].Product_id){
               myArray[i].Quantity = parseInt(myArray[i].Quantity) + 1;
               localStorage.setItem('wishlist', JSON.stringify(myArray));
           }
    }
 }

如果你想传递一个数字:

 addAmount(Product_id, Quantity){
        let myArray= JSON.parse(localStorage.getItem('wishlist'));
            for(let i = 0; i < myArray.length; i++){
               if(Product_id == myArray[i].Product_id){
                   myArray[i].Quantity = Quantity;
                   localStorage.setItem('wishlist', JSON.stringify(myArray));
               }
        }
     }

P.S。对于这种数据,最好使用 Storage 而不是 localStorage

When running in a native app context, Storage will prioritize using SQLite, as it's one of the most stable and widely used file-based databases, and avoids some of the pitfalls of things like localstorage and IndexedDB, such as the OS deciding to clear out such data in low disk-space situations.

import { Storage } from '@ionic/storage';
...
constructor(public _storage: Storage){}
...
this._storage.get('wishlist').then((res) => {
     for(let i = 0; i < res.length; i++){
         if(Product_id == res[i].Product_id){
            res[i].Quantity = parseInt(res[i].Quantity) + 1;
            //res[i].Quantity = Quantity;
            this._storage.set('wishlist', res).then(()=>
                console.log(res)
            );
         }
     }
})

这不是 localStorage 的目的...请尝试 webStoragehttps://www.w3schools.com/html/html5_webstorage.asp