如何在事先不知道密钥的情况下检索所有 localStorage 项?

我想显示所有的密钥和存储写之前。 我的代码在下面。我创建了一个函数(allStorage) ,但它不能工作。 我怎么能这么做?

    function storeUserScribble(id) {
var scribble = document.getElementById('scribble').innerHTML;
localStorage.setItem('userScribble',scribble);
}


function getUserScribble() {
if ( localStorage.getItem('userScribble')) {
var scribble = localStorage.getItem('userScribble');
}
else {
var scribble = 'You can scribble directly on this sticky... and I will also remember your message the next time you visit my blog!';
}
document.getElementById('scribble').innerHTML = scribble;
}


function clearLocal() {
localStorage.clear();
return false;
}


function allStorage() {
var archive = [];
for (var i = 0; i<localStorage.length; i++) {
archive[i] = localStorage.getItem(localStorage.key(i));
}
}
144063 次浏览

localStorage不是一个数组,而是一个对象,所以试试这样做:

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

如果你把你的函数修改成这样,你可以根据键列出所有的项目(只列出项目) :

function allStorage() {


var values = [],
keys = Object.keys(localStorage),
i = keys.length;


while ( i-- ) {
values.push( localStorage.getItem(keys[i]) );
}


return values;
}

Object.keys 是对 JavaScript (ECMAScript 5)的新增加。它列出了一个对象上的所有自己的键,这比使用 for-in 循环快,for-in 循环是这个对象的选项。

但是,这不会显示密钥。为此,你需要返回一个对象而不是数组(这是相当没有点的 IMO,因为这将带给你像以前一样的 localStorage 只是一个不同的对象-但例如的缘故) :

function allStorage() {


var archive = {}, // Notice change here
keys = Object.keys(localStorage),
i = keys.length;


while ( i-- ) {
archive[ keys[i] ] = localStorage.getItem( keys[i] );
}


return archive;
}

如果你想要一个紧凑的格式列表,那么就这样做吧——这里数组中的每个条目都有 key=item,稍后你可以把它们分成对,依次类推:

function allStorage() {


var archive = [],
keys = Object.keys(localStorage),
i = 0, key;


for (; key = keys[i]; i++) {
archive.push( key + '=' + localStorage.getItem(key));
}


return archive;
}
// iterate localStorage
for (var i = 0; i < localStorage.length; i++) {


// set iteration key name
var key = localStorage.key(i);


// use key name to retrieve the corresponding value
var value = localStorage.getItem(key);


// console.log the iteration key and value
console.log('Key: ' + key + ', Value: ' + value);


}

更简洁一点:

function getAllLocalStorage() {
return Object.keys(localStorage)
.reduce((obj, k) => {
return { ...obj, [k]: localStorage.getItem(k)}}, {});
}

最简单的方法是:

return JSON.stringify(localStorage);

ES2015 + 中最简单的方法是:

const items = { ...localStorage };
for (let [key, value] of Object.entries(localStorage)) {
console.log(`${key}: ${value}`);
}

These are all bulky or downright incorrect.

正确答案是:
JSON.parse(JSON.stringify(localStorage))

这样获取 localStorage 键数组:

console.log('keys: ', localStorage._keys)

通过尝试“正确答案”可能很明显,但是如果您想遍历或搜索键名,localStorage._keys是您的简单起点。

要获取所有的“ localStorage”,请复制它并将本地存储设置到所需的位置

var localstorage= {...localStorage};
var content = 'localStorage.clear();';
$.each(localstorage,(i,e)=>{
content+=localStorage.setItem('${i}','${e}');})
副本(内容) < br/>