Javascript数组:如何检查两个连续单词是否相同

Javascript array: How to check if two consecutive words are the same?

本文关键字:连续 两个 单词 是否 何检查 数组 Javascript 检查      更新时间:2023-09-26

我希望我的程序检查数组中是否有任何两个连续的单词相同。我相信我的"if"语句是正确的,但是console.log显示所有连续的单词都匹配。我在这里错过了什么?

感谢您的帮助!我对这个东西不熟悉:)

var wordArray = ["blue", "green", "yellow", "red", "red", "blue", "blue", "yellow"]
for (i=0; i<wordArray.length - 1; i++) {
    if (i === i+1); {
        console.log("We have a match!");
    } //Why is this loop saying that all items in the array are equal?
}

试试这个。您检查的是索引,而不是数组的元素,旁边是错误的if语句。

for (i = 0; i < wordArray.length - 1; i++) {
    if (wordArray[i] === wordArray[i + 1]) {
        console.log("We have a match!");
    }
}

如果数组只有一个元素长,这只是一个更好的长度处理提示:

for (i = 1; i < wordArray.length; i++) {
    if (wordArray[i - 1] === wordArray[i]) {
        console.log("We have a match!");
    }
}

试试这个,

var wordArray = ["blue", "green", "yellow", "red", "red", "blue", "blue", "yellow"]
for (i=1; i<wordArray.length; i++) {
    if (wordArray[i] === wordArray[i-1]) {
        console.log("We have a match!");
    }
}

看起来您实际上是在将代码中的索引var"i"与"i+1"进行比较,结果控制台显示数组中的所有项都相等。由于您实际上是在比较索引var,您的Javascript将其显示为:

if(1 === 2) 
    console.log("We have a match");

由于您实际上想要比较wordArray的内容:

if(wordArray[i] === wordArray[i + 1])
     console.log("We have a match!");

这里需要记住的重要一点是,当使用"for"循环时,索引变量"i"在本例中仅是用于访问数组内容的整数索引。