Chaos Chaos - 26 days ago 8
Javascript Question

Strange output while Looping through localstorage

Im trying to insert items into the localStorage and loop through it this is the code

localStorage.setItem(1,'Lorem');
localStorage.setItem(2,'Ipsum');
localStorage.setItem(3,'Dolor');
for(var i in window.localStorage){
console.log(i);
}


this is what I get as output on Firefox it seems to work fine on Chrome

3
2
1
key
getItem
setItem
removeItem
clear
length


the output seems to be the 3 values + the functions and length of the local storage I only want to output my values.
A for localstorage.length loop cant be used because I plan to insert and delete values.

Answer

You need to check if it's not a property inherted from the object, like length, prototyped functions, etc...
So you need to call hasOwnProperty on the object, before continuing on the object.

for(var i in window.localStorage){
   if(window.localStorage.hasOwnProperty(i)) {
    console.log(i);
   }

}