簡體   English   中英

如何檢查特定數組的值並增加或減少它?

[英]How do I check values of a particular array and increment or decrements it?

我有一個存儲在本地存儲中的數組中的購物籃。 如何檢查特定值是否增加或減少值

這是我的代碼

我想檢查 ProductID 是否存在,然后從中添加或減去,然后更新 localstorage

var Basket = {
    ProductID: product,
    Quantity: quantity
};

//STEP 2 - create an array 
//  
var BasketContents = [];
if (localStorage.getItem('BasketContents') != null) {
    BasketContents.push(JSON.parse(localStorage.getItem('BasketContents')));
}

//STEP 3 - create array of objects
BasketContents.push(Basket);
localStorage.setItem('BasketContents', JSON.stringify(BasketContents));

您可以通過保存對象的對象(稱為 object ALL)來解決此問題,其中 productId 作為對象中每個 object 的鍵(對象 ALL)或對象數組(每個籃子)。 第二個(對象數組)感覺更直觀,所以我會解釋一下。

  1. 獲取您需要的所有籃子並將它們放在一個數組中,如下所示:
const basket = [{productId: 2, quantity:5}, {productId: 6, quantity: 4}, {productId: 4, quantity: 18}, {productId: 3, quantity: 5}]
  1. 將購物籃保存在 localStorage 中:```localStorage.setItem('basketContainer', JSON.stringify(basket))```

  2. 每當您需要更新此列表/數組時,請從 localStorage 獲取 basketContainer 並循環遍歷它。

const update = JSON.parse(localStorage.getItem('basketContainer'))
update.forEach(x => {if (x.productId == 4) {x.quantity+=1}})

您可以在此時控制台更新,您會看到更改。

請也申請相同的減量。

您可以創建一個 function ,如:

const incrementDecrement = (list, action){ update.forEach(x => {if (x.productId == 4) {x.quantity`${action}`=1}})
}
// Where action is what determines if it is an increment(+) or decrement(-)
```

4. Once you're done, you can save the data back in your localStorage with the same initial name as it just overwrites the initial one.

something like this: ```localStorage.setItem('basketContainer', JSON.stringify(update))````

Goodluck!
By the way, you might want to read this: [stop_using_localStorage][1]


  [1]: https://dev.to/rdegges/please-stop-using-local-storage-1i04

我認為這是做到這一點的簡單方法

如果存儲的數據是這樣的{ ProductID: 241, Quantity: quantity }

//check if BasketContents exists
if(localStorage.BasketContents){
    // if exists
    let BasketContents = JSON.parse( localStorage.BasketContents );
    // add 5 to productId
    BasketContents.ProductID += 5;
    // then update localstorage
    localStorage.BasketContents = JSON.stringify(BasketContents);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM