javascript Localstorage:在使用 stringify 时计算 key 中有多少个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8093625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Localstorage: Count how many values in key when using stringify
提问by jQuerybeast
How can I count how many different values I have in 1 localstorage key.
我如何计算 1 个本地存储键中有多少个不同的值。
For example:
例如:
This is my localstorage:
这是我的本地存储:
[{"id":"item-1","icon":"google.com"},{"id":"item-2","icon":"youtube.com"}]
For this example I'd like an alert of 2 different values. So basically I want to count the {}
..
对于此示例,我想要 2 个不同值的警报。所以基本上我想计算{}
..
Is that possible?
那可能吗?
回答by Niet the Dark Absol
localStorage
is an object, so just localStorage.length
gives you the number of entries.
localStorage
是一个对象,所以只localStorage.length
给你条目的数量。
However I think I might be misunderstanding you. Do you mean you have one key, and that key's value is a JSON.stringify
'd object? If so, you could do JSON.parse(localStorage.keyname).length
to unserialise the value and count how many there are in there.
不过我想我可能误解了你。你的意思是你有一个键,那个键的值是一个JSON.stringify
'd 对象吗?如果是这样,您可以JSON.parse(localStorage.keyname).length
对值进行反序列化并计算其中有多少。
回答by Kevin Anthony Oppegaard Rose
Your object is saved as an array so just using the .length should give you the number of {} pairs you have. Try this (replace "whatever" with the name of your array:
您的对象保存为数组,因此只需使用 .length 即可获得您拥有的 {} 对数。试试这个(用你的数组名替换“whatever”:
var something = localstorage.whatever[];
var length = something.length;
alert("length = " + length);
回答by Graeme Leighfield
This will return the number of items in the key for you
这将为您返回密钥中的项目数
testing = JSON.parse(localStorage.getItem(KEYNAMEHERE));
//Lets count how many we have back
obj = eval('(' + testing + ')');
//And the total is...
objCount=0;
for(_obj in obj) objCount++;
alert(objCount)