获取HTML5 localStorage密钥 [英] Get HTML5 localStorage keys

查看:153
本文介绍了获取HTML5 localStorage密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如何获取 localStorage 中的所有关键值。




我试图用一个简单的JavaScript循环检索值

  for(var i = 1; i < = localStorage.length; i ++){
alert(localStorage.getItem(i))
}

但仅当密钥是渐进式数字时才有效,从1开始。






怎么做我得到所有的密钥,以显示所有可用的数据?

解决方案

  for localStorage中的var键){
console.log(key)
}

编辑:这个答案得到了很多upvotes,所以我想这是一个常见的问题。我觉得我应该对任何可能绊倒我的答案的人都认为这是正确的,只是因为接受了更新。事实是,上面的例子并不是真正的正确方式来做到这一点。最好和最安全的方式就是这样做:

  for(var i = 0,len = localStorage.length; i < len; ++ i){
console.log(localStorage.getItem(localStorage.key(i)));
}


I'm just wondering how to get all key values in localStorage.


I have tried to retrieve the values with a simple JavaScript loop

for (var i=1; i <= localStorage.length; i++)  {
   alert(localStorage.getItem(i))
}

But it works only if the keys are progressive numbers, starting at 1.


How do I get all the keys, in order to display all available data?

解决方案

for (var key in localStorage){
   console.log(key)
}

EDIT: this answer is getting a lot of upvotes, so I guess it's a common question. I feel like I owe it to anyone who might stumble on my answer and think that it's "right" just because it was accepted to make an update. Truth is, the example above isn't really the right way to do this. The best and safest way is to do it like this:

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  console.log( localStorage.getItem( localStorage.key( i ) ) );
}

这篇关于获取HTML5 localStorage密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆