使用indexOf在for循环中将字符串与数组中的内容匹配,错误

Matching string with things from array in a for loop with indexOf, error

本文关键字:错误 数组 indexOf for 循环 字符串 使用      更新时间:2023-09-26

我有一个小问题,从数组中查找和显示字符串。我好几年没写代码了,有点生疏了。我的问题是:

假设我有一个这样的数组:

var titles = ["0","Little Mouse", "1","Shaman Disciple", "2","Accomplished Shaman", "3","Shaman", "4","Little Pixie"];

(标题前面的数字是使用的标题id,我只是使用title [I -1]来获取它,它们的顺序是很重要的!)

我想找到数组中包含"little"的每个字符串并显示其对应的数字。我想到了这个,但它行不通,我已经试着读了很多关于循环和重写的东西,但我就是不明白。我写了这个脚本:

var x=document.getElementById("title").value;
var xs=x.toLowerCase();
    for(var i = 0; i <= titles.length; i++){
        if(xs.indexOf(titles[i].toLowerCase()) != -1){
            document.getElementById("command").innerHTML = "/title " + titles[i-1];
        } else {
            document.getElementById("command").innerHTML = "no title like that";
        }
    }

它被设置为onkeyup="dostuff()"上的文本字段(我知道不能是健康或良好的代码,但无论如何),它确实工作,如果你把完整的字符串,它只是不显示在数组中的所有匹配。我知道我应该使用innerHTML += blahblah而不是innerHTML = blahblah,但它只是无限期地增加了标题!我到底该怎么办
对不起,文字墙!

欢迎回到编程和StackOverflow。现在有大量可用的资源,特别是如果你正在使用JavaScript。

现在大多数浏览器都包含内置调试器和其他有用的开发工具。

还有一些在线资源,您可以在其中编写和测试代码,而不必担心托管。一个流行的是JSFiddle.net。

我在你的代码中发现了几个问题:

  1. 您的循环索引增加i变量的次数太多。
  2. 调用indexOf时,xstitles变量的顺序与需要的顺序相反。
  3. 你需要忽略空白的xs,因为它总是匹配。
  4. 你需要以某种方式累积匹配项,并在退出循环后输出它们。

修复后,代码看起来像这样:

var x=document.getElementById("title").value;
var xs=x.toLowerCase();
var found = [];
if (xs) {
    // was "i <= titles.length"
    for (var i = 0; i < titles.length; i++){
        // was "xs.indexOf(titles[i].toLowerCase())"
        if (titles[i].toLowerCase().indexOf(xs) != -1){
            // need to add items to list here
            found.push(titles[i - 1]);
        }
    }
}
// this logic needs to be outside of loop
if (found.length > 0) {
    document.getElementById("command").innerHTML = "/title " + found.join();
} else {
    document.getElementById("command").innerHTML = "no title like that";
}

在JSFiddle.net: http://jsfiddle.net/qa4x7b8t/4/

再次欢迎来到StackOverflow。请一定要投票并接受有用的答案。

你想在titles[i]中找到xs的索引,但你在xs中寻找标题。

应该是titles[i].toLowerCase().indexOf(xs) != -1

查看您的解决方案For循环运行的长度应小于数组的长度,且字符串应在For循环结束时被替换

var titles = ["0","Little Mouse", "1","Shaman Disciple", "2","Accomplished Shaman", "3","Shaman", "4","Little Pixie"];
var x="Little";  //test string
var serchStr=''; 
var xs=x.toLowerCase();
for(var i = 0; i <titles.length; i++){
    if(titles[i].toLowerCase().indexOf(xs) >-1){
        serchStr += "/title " + titles[i-1];
    } 
}
if(serchStr=='')
    serchStr = "no title like that";
alert(serchStr);

给你:

function findInRetardedArray(find, retardedArray){
  var r = [], f = new RegExp(find, 'i');
  for(var i=0,l=retardedArray.length; i<l; i+=2){
    if(retardedArray[i].match(f)){
      r.push(retardedArray[i]);
    }
  }
  return r;
}
// run the below on an Event instead of in the console
console.log(findInRetardedArray(document.getElementById('title').value, titles));