javascript 从 LocalStorage 检索所有数据(不知道密钥名称)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9144982/
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
Retrieve all data from LocalStorage (without knowing the key name)
提问by wezternator
I'm looking for a way to get all the information out of localStorage. The trouble I'm having is I don't know what the data will be as it is user generated.
我正在寻找一种从 localStorage 中获取所有信息的方法。我遇到的麻烦是我不知道数据是什么,因为它是用户生成的。
So here what happens, a user inputs some text, it uses javascript to manipulate it depending on what check boxes they have ticked on the input form. these boxes are for symbols for example if they tick the box for @ then the text + the @At (symbol then word) will be placed in local storage with the other half of the pair as a Boolean (1 or 0 in this case) representing whether its been checked.
所以这里会发生什么,用户输入一些文本,它使用javascript根据他们在输入表单上勾选的复选框来操作它。这些框用于符号,例如,如果它们勾选 @ 框,则文本 + @At(符号然后是单词)将被放置在本地存储中,另一半作为布尔值(在这种情况下为 1 或 0)表示它是否被检查。
the exact pair would look like this:
确切的一对看起来像这样:
someString..@At ???????| 1
someString..#Hash ????| 0
someString..@At ???????| 1
someString..#Hash ????| 0
etc.
等等。
It should also be noted that this is intended to be used in a Chrome Extension so compatibility in other browsers is not a requirement for me (although it could well be usful to others reading this as I can't find anything else covering it on the web).
还应该注意的是,这旨在用于 Chrome 扩展程序,因此我不需要在其他浏览器中兼容(尽管它可能对其他阅读本文的人很有用,因为我在网)。
So, if there anyway I can extract all the values in localStorage without actually knowing the name of each key? Is it possible to use any kind of wild card or regular expression maybe, I have tried this but should make it work using a for loop.
那么,如果无论如何我都可以在不知道每个键的名称的情况下提取 localStorage 中的所有值?是否可以使用任何类型的通配符或正则表达式,我已经尝试过,但应该使用 for 循环使其工作。
Thanks, Wez
谢谢,韦兹
回答by noob
window.localStorage.key is the solution. Example:
window.localStorage.key 是解决方案。例子:
var i = 0,
oJson = {},
sKey;
for (; sKey = window.localStorage.key(i); i++) {
oJson[sKey] = window.localStorage.getItem(sKey);
}
console.log(oJson);