![](/img/trans.png)
[英]How to get batch of array value from an array by incremental or decrements values
[英]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)或对象数组(每个篮子)。 第二个(对象数组)感觉更直观,所以我会解释一下。
const basket = [{productId: 2, quantity:5}, {productId: 6, quantity: 4}, {productId: 4, quantity: 18}, {productId: 3, quantity: 5}]
将购物篮保存在 localStorage 中:```localStorage.setItem('basketContainer', JSON.stringify(basket))```
每当您需要更新此列表/数组时,请从 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.