我是javascript的新手,并且在我的Hangman游戏中显示猜测的字母时出现问题。当用户点击"猜测"按钮,checkinput()方法应该启动,这应该运行:
//loop through word and if guess equals the character of the inputted work, replace - with letter.
for (i = 0; i < input.length; i++) {
//if user's guess is matched against one of the letters of the word, this will execute.
if (guess == input.substring(i, i + 1)) {
placeholder = placeholder.substring(0, i) + guess + placeholder.substring(i + 1, placeholder.length);
spguess.innerHTML = placeholder;
//if guessed letter is wrong, push into wrongg array
} else if (guess != input.substring(i, i + 1)){
wrongg.push(guess);
console.log(wrongg);
}
}
}
其他部分是我遇到问题的地方。我希望能够安装猜测的字母(错误的字母与输入的单词不匹配)。你能指出我正确的方向吗? https://jsfiddle.net/gdbn47or/是jsfiddle
答案 0 :(得分:0)
我觉得你有问题,因为你在你的周期中有你的wrongg.push,所以即使猜测是正确的第四个字母,它仍然会进入错误的数组3甚至更多次,你应该做什么对于每个循环,你应该有一个布尔值(找到),然后将你的if改为:
if (guess == input.substring(i, i + 1)) {
placeholder = placeholder.substring(0, i) + guess + placeholder.substring(i + 1, placeholder.length);
spguess.innerHTML = placeholder;
found = true;
}
如果找到的布尔值为假,则只在for循环后执行else if else