循环&搜索 localStorage 中的所有项目 [英] Loop & search through ALL items in localStorage
问题描述
我正在尝试遍历 localStorage 以通过与我的搜索算法一起使用的 localStorage.length
获取所有项目.如果我改变:i
for (i=0; i<100; i++)
而不是: (i=0; i<=localStorage.length-1; i++)
, everthing 有效.但是,我确实意识到问题可能出在搜索算法上.
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.
获取所有项目的代码:
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;
}
}
我的localStorage.length
有什么问题,或者搜索算法有什么问题?
What is wrong with my localStorage.length
, or what is wrong with the search algorithm?
推荐答案
问题现已解决.问题是,每次将数据保存到 localStorage 时,由于 for 循环(在 setItem 部分)写入错误,都会在本地数据库的底部存储一个额外的空项目.guestData.length 应该是 arrayIndex <来宾数据.length-1.数组索引
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).
这篇关于循环&搜索 localStorage 中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!