2016-07-19 30 views
0

我是新來的JavaScript和我有在我的劊子手遊戲顯示猜字母的問題。當用戶點擊「猜測」按鈕,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); 
      } 
     } 
    } 

的else if部分就是我遇到的問題。我想能夠console.log猜測的字母(不正確的字母不匹配輸入的單詞)。你能指出我正確的方向嗎? https://jsfiddle.net/gdbn47or/ is jsfiddle

+2

難道你不能只是'input.indexOf(guess)'? – gcampbell

+1

事實上,正如@ gcampbell所提到的,你對這個問題的處理方法是不正確的。你不需要循環 - 你可以用'string.indexOf(character)'查找用戶輸入的字符。或者,在現代瀏覽器上,如果您只想檢查一個'String'是否包含'Character',則可以編寫'String.includes(character)'。例如:''hello「.includes(」l「)'將返回'true'。 (但只有在現代瀏覽器中才支持) –

回答

0

你有問題,我認爲是因爲你在循環中有你的錯誤g.push,所以即使當第四個字母的猜測是正確的,它仍然會輸入錯誤的數組3或更多次,你應該做的是,你應該有一個布爾(找到),然後更改每個週期你如果到:

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循環的一部分,如果找到的布爾是假