Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop & search through ALL items in localStorage

I'm trying to loop through localStorage to get ALL items through localStorage.length that works with my search algorithm. If i change: i < localStorage.length inside the for loop to simply a number, i.e: for (i=0; i<100; i++) instead of: (i=0; i<=localStorage.length-1; i++), everthing works. However, I do realize the problem might lie in the search algorithm.

The code getting all items:

   var name = new Array();

   for (var i = 0; i <= localStorage.length - 1; i++) { // i < 100 works perfectly
   key = localStorage.key(i);
   val = localStorage.getItem(key); 
   value = val.split(","); //splitting string inside array to get name
   name[i] = value[1]; // getting name from split string
   }

My working (!?) search algorithm:

 if (str.length == 0) { 
  document.getElementById("searchResult").innerHTML = "";
  }   
  else {          
      if(str.length > 0) {
          var hint = "";
          for(var i=0; i < name.length; i++) {                
                if(str.toLowerCase() == (name[i].substr(0, str.length)).toLowerCase()) { //not sure about this line
                    if(hint == "") {                            
                            hint = name[i];                         
                        } else {                            
                            hint = hint + " <br /> " + name[i];                                 
                        }                 
                   }                      
             }            
       }          
}

 if(hint == "") {   
document.getElementById("searchResult").innerHTML=str + " står inte på listan";     
} else {        
    document.getElementById("searchResult").innerHTML = hint;       
    }
 }

What is wrong with my localStorage.length, or what is wrong with the search algorithm?

like image 730
Jonathan Avatar asked Apr 10 '12 04:04

Jonathan


2 Answers

localStorage is an object, not an array. Try for(var i in window.localStorage):

for(var i in window.localStorage){
   val = localStorage.getItem(i); 
   value = val.split(","); //splitting string inside array to get name
   name[i] = value[1]; // getting name from split string
}
like image 83
user2428118 Avatar answered Nov 08 '22 18:11

user2428118


Problem now SOLVED. The issue was that each time data was saved to localStorage, one extra empty item was stored at the bottom of the local db as a consequence of an incorrectly written for loop (in the setItem part.) arrayIndex < guestData.length should have been arrayIndex < guestData.length-1. arrayIndex < guestData.length-1 stores all items without creating an empty item at the bottom of the database which later messed up the search algorithm, as the last value to be search was undefined (the empty item).

like image 33
Jonathan Avatar answered Nov 08 '22 18:11

Jonathan