[英]Angular2/JavaScript - How can I show all the localStorage saved variables and get the total length of all keys?
I am working on an Angular2 app, in which I need to store items that were added by the user to the shopping cart. 我正在开发一个Angular2应用程序,我需要将用户添加的项目存储到购物车中。 For that, I am using local storage to save the items temporarily.
为此,我使用本地存储暂时保存项目。 Each category (ex. shoes, clothes....) is saved in the local storage as a key;
每个类别(例如鞋子,衣服......)都作为钥匙保存在本地存储器中; its value is an array that contains all the added items and belongs to the same category
key
. 它的值是一个包含所有添加项的数组,属于同一个类别
key
。
I have multiple keys, each of them has a value which is an array. 我有多个键,每个键都有一个数组值。 I want to access to the stored keys and also get the length of value of all keys
我想访问存储的密钥,并获得所有密钥的值的长度
Ex: key 1 has a value that has a length of 5. Key 2 has a value that has a length of 12. 例如:键1的值为长度5.键2的值为12。
So the total length is 12+5=17 所以总长度是12 + 5 = 17
Any idea on how to achieve that? 有关如何实现这一点的任何想法?
Why not just store it all on an object and JSON.stringify it to save, JSON.parse to load (Angular2 may have a better method of accessing localstorage). 为什么不将它全部存储在一个对象上,JSON.stringify它保存,JSON.parse加载(Angular2可能有更好的方法来访问localstorage)。
var store = {
"categories" : {
"shoes" : ['key1', 'key2'],
"clothes" : []
}
}
function getCategoryLength(cat){
var total = 0;
for(var i = 0; i < store.categories[cat].length){
total += store.categories[cat][i].length;
}
return total
}
getCategoryLength("shoes")
you can access keys with Object.keys
like below 您可以使用
Object.keys
访问密钥,如下所示
var storedKeys = Object.keys(localStorage);
//length = storedKeys.length
/*
//Assuming your have store structure like below
localStorage = {
key1: [1, 2, 3],
key2: [1, 2, 3, 4, 5],
key3: "text"
};
*/
var flattenKeysLength = 0;
for(var key in localStorage)
flattenKeysLength +=
(typeof localStorage[key] == "string")? 1:localStorage[key].length;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.