I want to show all of the keys and storage written before. My code is below. I created a function (allStorage) but it doesn't work. How can I do this?
function storeUserScribble(id) {
var scribble = document.getElementById('scribble').innerHTML;
localStorage.setItem('userScribble',scribble);
}
function getUserScribble() {
if ( localStorage.getItem('userScribble')) {
var scribble = localStorage.getItem('userScribble');
}
else {
var scribble = 'You can scribble directly on this sticky... and I will also remember your message the next time you visit my blog!';
}
document.getElementById('scribble').innerHTML = scribble;
}
function clearLocal() {
localStorage.clear();
return false;
}
function allStorage() {
var archive = [];
for (var i = 0; i<localStorage.length; i++) {
archive[i] = localStorage.getItem(localStorage.key(i));
}
}
The easiest way
return JSON.stringify(localStorage);
localStorage
is not an array, but an object, so try sth. like this:The easiest way in ES2015+ is:
A little more succinct:
If you modify your function to this you can list all items based on key (will list the items only):
Object.keys
is a new addition to JavaScript (ECMAScript 5). It lists all own keys on an object which is faster than using a for-in loop which is the option to this.However, this will not show the keys. For that you need to return an object instead of an array (which is rather point-less IMO as this will bring you just as far as you were before with localStorage just with a different object - but for example's sake):
If you want a compact format listing then do this instead - here each item in the array will have
key=item
which you later can split into pairs and so forth: