2016-11-22 3 views
-2

다시 : 행맨 게임index 올바른 색인을 반환하지 않는 경우

목표 : 사용자가 문자를 추측 한 후 단어의 문자 색인을 검색합니다.

문제 : 반환 된 숫자가 올바른 단어 색인이 아닙니다. 코드의 마지막 줄부터 3 번째 줄입니다.

저는 초보자입니다. 제발 쉽게가주세요. :) 너무 힘들어요!

// JavaScript Document 


$(document).ready(function() {  // upon page load 

    var badGuesses; // reset bad guess counter 
    var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Z"]; // array of letters to choose 
    $("#lettersRemaining").html(alphabet); // gets elements of the alphabet array and displays on UI 

// N E W G A M E B U T T O N C L I C K E D 

$("#newGame").click(function() { // when user clicks on Start New Game button... 

    $("#status").hide(); // upon game reset hide the status section stating game over 
    badGuesses = 0; // reset guess counter which is used later 
    var wordCollection = ["mansion", "statue", "gorilla", "notebook", "smartphone", "illustration", "photo", "elegant", "arborist", "keyboard", "calendar", "capital", "textbook", "horrible", "library"]; // array of words 
    var theWord = wordCollection[Math.floor(Math.random()*wordCollection.length)]; // randomly selects a word 
     console.log("theWord is ...."); 
     console.log(theWord); 

    var theWordLength = theWord.length;  // Get number of characters in randomly selected word 
     console.log("theWordLength is ...."); 
     console.log(theWordLength); 

// D I S P L A Y D A S H E S 

    var combineDashes = []; // creates an array to hold the number of dashes inside the for loop 
    for (var i = theWordLength; i > 0; i--) 
     { 
      combineDashes.push(" - "); // each loop through adds a dash to the array 
     } 
    combineDashes.join(" "); // joins cumulative dashes and converts to a string 
    $("#dashes").html(combineDashes); // displays dashes on UI 

}); 


// G U E S S L E T T E R 

$("#guessLetter").click(function(theWord) {  // when user clicks on the Guess Letter button pass in theWord value .... 
    var letter = $("#theLetter").val(); // gets the letter the user is guessing 
    console.log("letter is ..."); 
    console.log(letter); 

    // Is the letter a good or bad guess? 
    var letterContained = theWord.toString().indexOf(letter); // <-- NOT WORKING!! returns index from theWord for the letter guessed; -1 means bad guess 
    console.log("letterContained is..."); 
    console.log(letterContained); 


}); 

}); 
+0

toString()을 사용하지 않고 theWord.indexOf를 사용해 보셨습니까? –

+0

알파벳이 대문자이고 단어가 소문자이며 indexOf가 대소 문자를 구분한다고 생각합니다. –

+0

내 직감이 맞다면 theWord = wordCollection [여기에서 선택]을 설정하면 .toUpperCase()가 도움이됩니다. –

답변

0

이 모든 위의 의견이지만, 문제는 theWord가 badGuesses와 같은 수준에서 선언 (및 할당하지만 단지 badGuesses 같은 newGame에 선언되지 않음) 매개 변수로 제거 할 필요가 있다고했다 추측하기 더. 그런 다음 guessLetter는 theWord의 원하는 값을 가지며 indexOf 호출이 작동했습니다.