2017-12-03 7 views
0

私は非常にです。間違った用語を使用している場合は、Javascriptで新しいです。javacriptで無作為に選択された変数を維持する

私の授業では、コンピュータがどのような文字を推測しているのかを推測しなければならないゲームを作成する必要があります。

私が苦労しているのは、ユーザーが推測するたびに新しい文字を選択するのではなく、配列から1文字を選択して静的に保つ方法です。ここに私のコードはありますか?

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','y','z']; 



document.onkeyup = function() { 
    var userguess = 
     String.fromCharCode(event.keyCode).toLowerCase(); 
    console.log(userguess); 


var computerGuess = 
    alphabet[Math.floor(Math.random() * alphabet.length)] 
console.log(computerGuess); 

} 
+0

単にあなたの 'keyup'イベントハンドラこれが働い – blex

答えて

3

あなたのcomputerGuessをイベントハンドラの外に持ち出してください。あなたは、各keyupに新しい値を生成している:

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', 'y', 'z']; 
 

 
var computerGuess = alphabet[Math.floor(Math.random() * alphabet.length)]; 
 

 
document.onkeyup = function() { 
 
    var userguess = String.fromCharCode(event.keyCode).toLowerCase(); 
 
    
 
    console.log(`userguess: ${userguess}, computerGuess: ${computerGuess}`); 
 
}

+1

の外で、あなたの' computerGuess'変数宣言を動かします!ありがとうございました! –

関連する問題