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

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

我在查找和显示数组中的字符串时遇到了一点问题。多年来没有编写任何类型的代码,所以我有点生疏。我的问题是:

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

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

(标题前的数字是使用的标题id,我只是使用标题[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,但它只会无限期地添加到标题中!我到底要做什么
对不起文字墙!

您想在 titles[i] 中查找 xs 的索引,但您要在 xs 中查找标题。

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

请参阅此 fiddle 以获得您的解决方案 Link to fiddle for循环应该运行小于数组的长度不等于并且string应该在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));

欢迎回到编程和 Whosebug。这些天有大量可用资源,特别是如果您使用 JavaScript.

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

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

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

  1. 您的循环索引使 i 变量增加了太多次。
  2. 调用 indexOfxstitles 变量的顺序与它们需要的顺序相反。
  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/

再次欢迎来到 Whosebug。有用的答案请务必点赞采纳