2016-11-19 6 views
1

私はHangmanのゲームに取り組んでいるJavascriptの学生です。秘密の単語の正しいダッシュの数を表示する私のループは機能していません。毎回1つのダッシュだけを表示します。 ヘルプは高く評価されています。ありがとうございました。Hangman - 正しいダッシュの数は表示されません

$(document).ready(function(e) { 
    // array of letters to choose 
    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"]; 

    $("#lettersRemaining").html(alphabet); 


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

    // array of words 
    var wordCollection = ["mansion", "statue", "gorilla", "notebook", "smartphone", "illustration", "photo", "elegant", "arborist", "keyboard", "calendar", "capital", "textbook", "horrible", "library"]; 

    // randomly select a word from the wordCollection array 
    var theWord = wordCollection[Math.floor(Math.random()*wordCollection.length)]; 
     console.log("theWord is ...."); 
     console.log(theWord); 

    // Get index location of the word randomly selected above  -- Not sure I even need index..?? 
    var theWordIndex = wordCollection.indexOf(theWord); 
     console.log("theWordIndex is ...."); 
     console.log(theWordIndex); 

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


    // display a dash equal to the theWordLength 
    for (var i = theWordLength; i > 0; i--) 
    { 
     $("#dashes").html(" - "); 
    } 
+1

あなたがそれに追加して、HTMLを毎回ではない設定しています。 –

+1

要素の内容として1つのダッシュを複数回設定しています。最初に文字列変数に必要な数のダッシュをアセンブルしてから、それを割り当てるか、またはinnerHTML + =を使用してください。 – CBroe

答えて

1

問題はここにある: $("#dashes").html(" - ");

あなたはすべての繰り返しで#dashesの内部HTMLをオーバーライドしています。あなたが必要とするのは、現在のコンテンツを新しいダッシュで「連結」する(2つの文字列を結合する)ことです。

より実践的な側面では、DOMアクセスはパフォーマンス上非常に有害です。一般的にループに入れないでください。ベストプラクティスは、実行する前にできるすべてのDOM変更を計算することです。あなたの場合は、dashes変数を準備し、ループの実行が終了したら#dashesの内容を設定します。

あなたが始めるためにいくつかの有用なリソース:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat

http://api.jquery.com/text/

http://api.jquery.com/html/

関連する問題