2016-11-22 211 views
-2

回覆:Hang子手遊戲indexOf沒有返回正確的索引

目標:用戶猜測一個字母后,檢索字中字母的索引。

問題:返回的數字不是單詞的正確索引。這是代碼的第三行。

我是一個新手,所以請容易我:)請這麼難!

// 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

你有沒有嘗試theWord.indexOf沒有toString() –

+0

我認爲你的字母是大寫,你的話是小寫和indexOf區分大小寫。 –

+0

如果我的預感是正確的,設置theWord = wordCollection [你在這裏選擇] .toUpperCase()應該有幫助 –

回答

0

這是所有在上面的意見,但問題是,theWord需要在同一水平badGuesses擬申報(並分配,但在newGame,就像badGuesses未申報),並作爲一個參數被移除猜猜信。然後guessLetter具有期望的WORD值,並且indexOf調用起作用。