Javascript 如何显示所有 localStorage 保存的变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5410820/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:05:18  来源:igfitidea点击:

How can I show all the localStorage saved variables?

javascripthtmllocal-storage

提问by Ariel

I want to acess all the localStorage variables saved on a specific page. How do I do that? I want to show it like I would show an array with the join() function

我想访问保存在特定页面上的所有 localStorage 变量。我怎么做?我想显示它就像显示一个带有 join() 函数的数组

回答by Greg

You could try iterating through all of the items in the localStorage object:

您可以尝试遍历 localStorage 对象中的所有项目:

for (var i = 0; i < localStorage.length; i++){
    // do something with localStorage.getItem(localStorage.key(i));
}

回答by Mark

I use this block of code frequently:

我经常使用这段代码:

var i;

console.log("local storage");
for (i = 0; i < localStorage.length; i++)   {
    console.log(localStorage.key(i) + "=[" + localStorage.getItem(localStorage.key(i)) + "]");
}

console.log("session storage");
for (i = 0; i < sessionStorage.length; i++) {
    console.log(sessionStorage.key(i) + "=[" + sessionStorage.getItem(sessionStorage.key(i)) + "]");
}

回答by jujule

you can also check localStorage status and data right in the Google chrome Developer tools

您还可以直接在 Google chrome 开发人员工具中检查 localStorage 状态和数据

回答by Ananta Prasad

Console log the localStorage. It's very simple.

控制台记录 localStorage。这很简单。

console.log(localStorage);

回答by zanetu

for(var i in localStorage) {
    console.log(i + ' = ' + localStorage[i]);
}

回答by Brook Jordan

Taking hints from this page, I'm now using this:

从这个页面得到提示,我现在正在使用这个:

new Array(localStorage.length)
  .fill()
  .map(i => localStorage.key(i));

Thanks all!

谢谢大家!

回答by NVRM

To extend this, the following retrieves everything in the localStorage.

为了扩展这一点,以下内容检索 localStorage 中的所有内容。

Regardless the type of the entry, object, array,or just a value.

无论条目、对象、数组的类型如何,或者只是一个

And write all well back in place.

并将所有内容写回原位。

Useful to save/export/restoreany given config!

用于保存/导出/恢复任何给定的配置!

function getLocalItems(k){
  if (k){
    try{
      return JSON.parse(localStorage.getItem(k))
     } catch(e){
       return localStorage.getItem(k)
    }
  }
}

function setLocalItems(k, value){
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  localStorage.setItem(k, value)
}

// Put all entries in an object ?store?
let store = {}
for (let i = 0, l = localStorage.length; i < l; i++) {
  store[localStorage.key(i)] = getLocalItems(localStorage.key(i))
}
console.log(store)

// Write all keys of ?store? in localStorage
for (let o in store) {
  setLocalItems(o, store[o])
}

You can then send this ?store? object to your server, for backup/restore after login.

然后你可以发送这个 ?store? 反对您的服务器,用于登录后的备份/恢复。

After experiments, in the case of heavy usage of the localStorage, it is a good idea to use this ?store? object in scripts, this keeps all values in memory for faster i/o access, because no hard write on disk.

经过实验,在大量使用localStorage的情况下,最好使用这个?store? 脚本中的对象,这会将所有值保留在内存中以加快 i/o 访问,因为没有硬写入磁盘。

Either way the localStorage is extremely powerful, we can make complex stuffs. Use it in a way that your scripts won't fail if the localStorage keys are missing or corrupted.

无论哪种方式 localStorage 都非常强大,我们可以制作复杂的东西。如果 localStorage 键丢失或损坏,您的脚本不会失败的方式使用它。

Allowing users to erase all local configs with a button or automatic after logout, is also a good idea!

允许用户在注销后通过按钮或自动删除所有本地配置也是一个好主意!

回答by Jan Papenbrock

I refined the script by Cryptopatto be copy+paste ready, and work with both localStorage as well as sessionStorage. This is handy to reproduce the full storage 1:1 on a different machine.

通过 Cryptopat改进了脚本以准备好复制+粘贴,并与 localStorage 和 sessionStorage 一起使用。这对于在不同的机器上以 1:1 的比例重现完整存储非常方便。

Tested on Chrome 74.0.3729.131.

在 Chrome 74.0.3729.131 上测试。

function dump(storage) {
    let store = []
    for (let i = 0, l = storage.length; i < l; i++) {
        let key = storage.key(i);
        store.push({ key: key, value: storage.getItem(key) });
    }
    console.log(JSON.stringify(store))
}

function restore(storage, store, clearBefore) {
    if (clearBefore) {
        storage.clear();
    }

    for (let i = 0, l = store.length; i < l; i++) {
        let item = store[i];
        storage.setItem(item.key, item.value);
    }
}

// usage:
// 
// dump(localStorage); // manual step: copy log output to text file
// dump(sessionStorage);
//
// let contentsFromTextFile = [ ... ]; // manual step: paste from text file
// restore(localStorage, contentsFromTextFile, true);
// restore(sessionStorage, contentsFromTextFile, true);
//
//
// EXAMPLE
// -------
// Given localStorage has one entry with key "foo" and value "bar"
// And I pasted the above code into the console
//
// When I run
//    dump(localStorage)
// Then I see the log output
//    [{"key":"foo","value":"bar"}]
//
// When I run
//    restore(localStorage, [{"key":"foo2","value":"bar2"}], true);
// Then localStorage contains only one entry with key "foo2" and value "bar2"
//
// When I run
//    restore(localStorage, [{"key":"foo3","value":"bar3"}], false);
// Then localStorage contains two entries,
//   one entry with key "foo2" and value "bar2" and
//   one entry with key "foo3" and value "bar3"