比较两个数组并在Javascript中找到匹配项

时间:2017-10-31 11:12:58

标签: javascript arrays loops

for(var i = 0; i < textList.length; i++){
    for(var j = 0; j < titles.length; j++){
        if(textList[i] === titles[j]){
            console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
        }
    }
}

这是我的代码,但它不会返回匹配项。我试过==和===。但是当我测试.includes()时它起作用了。有人能解释一下发生了什么吗?

2 个答案:

答案 0 :(得分:0)

如果您确定所有元素都是String类型,则可以使用方法.search():

Prototype search

它会返回匹配的位置,如果它在任何位置都匹配,你将获得-1作为返回,soo&gt; 0匹配。

答案 1 :(得分:0)

我刚用一个非常基本的测试示例测试了您的代码,如下所示:

let textList = ['book1', 'book2','book3']

let titles = ['book', ' tester', 'not_this', 'book2']

for(var i=0; i<textList.length;i++){
    for(var j=0; j<titles.length;j++){
        if (textList[i] === titles[j]){
            console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
        }
    }
}

我得到了预期的结果it includes my book2 the match is book2 counter 1所以使用这个特定的代码,我建议你看一下输入数组。

关于你.includes()为什么有效的问题而且这个问题没有问题,我们再次需要查看你的输入数组,但我会猜测它与内部的类型检查有关这个功能。

最后,正如其他人所建议的那样,还有其他(更简洁)的方法可以通过内置数组函数来实现这一点,但是您最初的问题是关于为什么这段代码特别无法工作所以我已经这样做了离开了这些。

相关问题