Get HTML5 localStorage keys

2019-01-03 04:57发布

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?

9条回答
冷血范
2楼-- · 2019-01-03 05:13

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

Array.apply(0, new Array(localStorage.length)).map(function (o, i) {
    return localStorage.key(i);
})
查看更多
干净又极端
3楼-- · 2019-01-03 05:17

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;
}
查看更多
爷、活的狠高调
4楼-- · 2019-01-03 05:19
function listAllItems(){  
    for (i=0; i<=localStorage.length-1; i++)  
    {  
        key = localStorage.key(i);  
        alert(localStorage.getItem(key));
    }  
}
查看更多
劫难
5楼-- · 2019-01-03 05:25

We can also read by the name.

Say we have saved the value with name 'user' like this

$localStorage.user = user_Detail;

Then we can read it by using

localStorage["ngStorage-user"];

I used it and it is working smooth, no need to do the for loop

查看更多
走好不送
6楼-- · 2019-01-03 05:27

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!)

查看更多
相关推荐>>
7楼-- · 2019-01-03 05:30

You can use the localStorage.key(index) function to return the string representation.

查看更多
登录 后发表回答