[英]I'm creating a hangman game in vanilla JS, and have stumbled across this error that I can't figure out the reason for
[英]Creating Simple Hangman Game in js and Can't get if statement read correctly
在下面的代碼中,如果玩家猜測的字母不在所選的秘密單詞中,我將無法執行代碼。 我已經設置了所以當點擊提交按鈕時,我們首先檢查猜出的字母是否在拼圖單詞中,如果是字母被翻轉,然后我試圖說如果它不在單詞中遠離玩家的生活。 我嘗試了幾種方法,但無法讓程序正確讀取第二個 if 語句。
submit.addEventListener('click', function(){
console.log("clicked");
usedLetters.innerHTML += playersLetter.value + ' '
for(i=0; i<checkWord.length; i++){
console.log(wordLife)
if(playersLetter.value == (checkWord[i])){
console.log('in if#1')
console.log(playersLetter.value)
var answerLetter = document.getElementsByClassName('letter')[i]
answerLetter.innerHTML = playersLetter.value
wordLife--
}
}
function scoreLetter(value){// To check if the letter is actually in the word
for(let i = 0; i < checkWord.length; i++){
if(value == (checkWord[i])){
return true
}else {
return false
}
}
}
console.log('read function')
if(scoreLetter(playersLetter.value) == false){
console.log('in 2nd if')
playerLife--
console.log(playerLife)
}
})
您的 scoreLetter 函數是錯誤的,您只檢查第一個字母,如果值不在第一個位置,則返回 false。 試試這個……檢查字母是否在數組中
function scoreLetter(value){
return (checkWord.indexOf(value) === -1) ? false : true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.