Question

I am trying to get the key for each item in local storage.

These are what I have stored so far:

'132', 'yes'
'15', 'yes'
'76', 'yes'

However, the following loop returns NULL:

 for(var i in localStorage){
     console.log(localStorage.getItem(localStorage.key(i)));

}

What would be the best way for me to get the key of one of the items listed?

Était-ce utile?

La solution

UPDATED:

for(var key in localStorage){
    console.log(key);
}

Or,

for (var i = 0; i < localStorage.length; i++){
    console.log(localStorage.key(i));
}

, that is if you'd like to track the index count in the loop.

Autres conseils

You can access the keys directly like so:

for (var key in localStorage) {
    if (localStorage.hasOwnProperty(key)) {
        console.log('Key:' + key);//Logs the key ex:132,15,76
        console.log('Value:' + localStorage[key]);//Logs the value ex:yes,yes
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top