循环&搜索 localStorage 中的所有项目 [英] Loop & search through ALL items in localStorage

查看:26
本文介绍了循环&搜索 localStorage 中的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历 localStorage 以通过与我的搜索算法一起使用的 localStorage.length 获取所有项目.如果我改变:i for 循环内的简单数字,即: 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).

这篇关于循环&amp;搜索 localStorage 中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆