Javascript 获取 HTML5 localStorage 键

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

Get HTML5 localStorage keys

javascripthtmlkeylocal-storage

提问by Simone

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

我只是想知道如何在localStorage.



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

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

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.

但它只有在键是渐进式数字时才有效,从 1 开始。



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

如何获取所有密钥,以显示所有可用数据?

采纳答案by nktshn

in ES2017 you can use:

在 ES2017 中,您可以使用:

Object.entries(localStorage)

回答by Kevin Ennis

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 rightway 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 ) ) );
}

回答by Zack Argyle

I like to create an easily visible object out of it like this.

我喜欢像这样创建一个容易可见的对象。

Object.keys(localStorage).reduce(function(obj, str) { 
    obj[str] = localStorage.getItem(str); 
    return obj
}, {});

I do a similar thing with cookies as well.

我也用饼干做类似的事情。

document.cookie.split(';').reduce(function(obj, str){ 
    var s = str.split('='); 
    obj[s[0].trim()] = s[1];
    return obj;
}, {});

回答by nerdcoder

function listAllItems(){  
    for (i=0; i<=localStorage.length-1; i++)  
    {  
        key = localStorage.key(i);  
        alert(localStorage.getItem(key));
    }  
}

回答by Jeffrey Sweeney

You can use the localStorage.key(index)function to return the string representation, where indexis the nth object you want to retrieve.

您可以使用该localStorage.key(index)函数返回字符串表示,其中index是您要检索的第 n 个对象。

回答by cillay

If the browser supports HTML5 LocalStorage it should also implement Array.prototype.map, enabling this:

如果浏览器支持 HTML5 LocalStorage,它也应该实现 Array.prototype.map,启用它:

Array.apply(0, new Array(localStorage.length)).map(function (o, i) {
    return localStorage.key(i);
})

回答by Sean Colombo

Since the question mentioned finding the keys, I figured I'd mention that to show every key and value pair, you could do it like this (based on Kevin's answer):

由于问题提到了找到键,我想我会提到要显示每个键和值对,你可以这样做(基于凯文的回答):

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

This will log the data in the format "key: value"

这将以“键:值”格式记录数据

(Kevin: feel free to just take this info into the your answer if you want!)

(凯文:如果您愿意,可以随意将这些信息纳入您的答案!)

回答by Hassan Azimi

I agree with Kevin he has the best answer but sometimes when you have different keys in your local storage with the same values for example you want your public users to see how many times they have added their items into their baskets you need to show them the number of times as well then you ca use this:

我同意凯文的看法,他有最好的答案,但有时当您的本地存储中具有相同值的不同密钥时,例如您希望您的公共用户查看他们将他们的物品添加到他们的购物篮中的次数,您需要向他们展示次数以及然后你可以使用这个:

var set = localStorage.setItem('key', 'value');
var element = document.getElementById('tagId');

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

回答by Rahim Naik

This will print all the keys and values on localStorage:

这将打印 localStorage 上的所有键和值:

ES6:

ES6:

for (let i=0; i< localStorage.length; i++) {
    let key = localStorage.key(i);
    let value = localStorage[key];
    console.log(`localStorage ${key}:  ${value}`);
}

回答by Admir

You can get keys and values like this:

您可以像这样获取键和值:

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