0

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?

2 Answers2

2

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.

Kyo
  • 974
  • 5
  • 10
  • Apologies, maybe I got the wording wrong. I'm trying to console.log the numbers, '132, '15', etc. The above code returns 'yes'. –  Apr 29 '14 at 10:04
1

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
    }
}
A1rPun
  • 16,287
  • 7
  • 57
  • 90
  • Apologies, maybe I got the wording wrong. I'm trying to console.log the numbers, '132, '15', etc. The above code returns 'yes'. –  Apr 29 '14 at 10:02