Localstorage:使用stringify时计算key中有多少个值

发布于 2024-12-15 03:25:34 字数 230 浏览 1 评论 0原文

如何计算 1 个本地存储键中有多少个不同的值。

例如:

这是我的本地存储:

[{"id":"item-1","icon":"google.com"},{"id":"item-2","icon":"youtube.com"}]

对于此示例,我想要 2 个不同值的警报。所以基本上我想计算{}..

这可能吗?

How can I count how many different values I have in 1 localstorage key.

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 {}..

Is that possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

如梦亦如幻 2024-12-22 03:25:34

localStorage 是一个对象,因此只需 localStorage.length 即可为您提供条目数。

不过我想我可能误解了你的意思。您的意思是您有一个键,并且该键的值是一个 JSON.stringify 对象吗?如果是这样,您可以执行 JSON.parse(localStorage.keyname).length 来反序列化该值并计算其中有多少个。

localStorage is an object, so just localStorage.length gives you the number of entries.

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.

百善笑为先 2024-12-22 03:25:34

您的对象保存为数组,因此只需使用 .length 就可以得到您拥有的 {} 对的数量。试试这个(将“whatever”替换为数组的名称:

var something = localstorage.whatever[];
var length = something.length;
alert("length = " + length);

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:

var something = localstorage.whatever[];
var length = something.length;
alert("length = " + length);
情绪 2024-12-22 03:25:34

这将为您返回密钥中的项目数

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文