localStorage.length
検索アルゴリズムで動作するすべてのアイテムを取得するために localStorage をループしようとしています。i < localStorage.length
for ループ内で: を単に数値に変更すると、つまり:for (i=0; i<100; i++)
の代わりに: (i=0; i<=localStorage.length-1; i++)
、すべてが機能します。ただし、検索アルゴリズムに問題がある可能性があることは認識しています。
すべてのアイテムを取得するコード:
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
}
私の作業中の (!?) 検索アルゴリズム:
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;
}
}
の何が問題localStorage.length
なのか、または検索アルゴリズムの何が問題なのか?