0

I'm trying to print the names of all the keys stored in localStorage with each key in a separate line. This is my code:

function viewsaved(){
    $('#saved').show();
    var stuffsaved = Object.keys(localStorage);
    var splitit = stuffsaved.split(',');
    for (var i = 0 ; i < splitit.length ; i++ ){
        $('#saved').append(splitit[i]+"<br>");
    }
}

when I call the function, it does nothing.

How do you do this properly?

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
chin123
  • 15
  • 6

1 Answers1

3

Object.keys returns an array, not a string. Just modify slightly:

var stuffsaved = Object.keys(localStorage);
for (var i = 0 ; i < stuffsaved.length ; i++ ) {
    $('#saved').append(stuffsaved[i]+"<br>");
}

If you have or expect a lot of keys, I would suggest building the list in a temporary variable first to avoid frequent DOM update, for example:

var keys = Object.keys(localStorage);
var list = "";

for (var i = 0 ; i < keys.length ; i++ ) {
    list += keys[i] + "<br>";
}

$('#saved').append(list);