循环并搜索localStorage中的所有项目

Jon*_*han 14 javascript arrays for-loop local-storage

我正在尝试遍历localStorage以获取所有通过localStorage.length我的搜索算法工作的项目.如果我改变:i < localStorage.length在for循环中只for (i=0; i<100; i++)改为一个数字,即:而不是:(i=0; i<=localStorage.length-1; i++),everthing工作.但是,我确实意识到问题可能在于搜索算法.

获取所有项目的代码:

   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
   }
Run Code Online (Sandbox Code Playgroud)

我的工作(!?)搜索算法:

 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;       
    }
 }
Run Code Online (Sandbox Code Playgroud)

我的错误localStorage.length或搜索算法有什么问题?

use*_*118 16

localStorage是一个object,而不是一个array.试试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
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*han 1

问题现已解决。问题是,每次将数据保存到 localStorage 时,由于错误地编写了 for 循环(在 setItem 部分中),本地数据库的底部会存储一个额外的空项。 arrayIndex < guestData.length 应该是 arrayIndex < guestData.length-1。arrayIndex < guestData.length-1 存储所有项目,而不在数据库底部创建空项目,这后来扰乱了搜索算法,因为要搜索的最后一个值未定义(空项目)。