gpt4 book ai didi

JavaScript 数组 : How to check if two consecutive words are the same?

转载 作者:行者123 更新时间:2023-11-29 16:54:00 25 4
gpt4 key购买 nike

我想让我的程序检查数组中任意两个连续的单词是否相同。我相信我的“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!");
}
}

关于JavaScript 数组 : How to check if two consecutive words are the same?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33810010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com