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?