0

だから私は次のコードを持っています:

var func1 = function() {
    var userChoose = prompt("Choose a number from 1-10. If you choose the same number as the computer, you win!");
    func2();
};

var func2 = function() {
    computerChoose = Math.random();
    computerChoose = Math.round(computerChoose*10)/10;
    if (userChoose === computerChoose) {
        console.log("You won! The computer chose the number " + userChoice + " just like you! Good job!");
    } else if (userChoose > 10) {
        console.log("I'm sorry, you wrote something above 10. Try again.");
    } else {
        console.log("Sorry! The computer got " + computerChoose + 
        " and you got " + userChoose + ". Sorry!");
    }
};

func1();

私が抱えている問題は、数字、たとえば 5 を配置すると、その数字のままになり、コードを実行するたびに「申し訳ありません。コンピューターは x を取得し、あなたは 5 を取得しました。」と表示されます。 .

私が間違っている場合は修正してください。ただし、関数内の変数を変更しようとしているためにこれが発生すると考えています。私の主な質問は、関数内にある変数をグローバル化して、さまざまな関数で使用および変更できるようにするにはどうすればよいですか?

ありがとうございました。

4

1 に答える 1

2

関数を呼び出すときに値を渡すことができます。これを試して:

var func1 = function() {
    var userChoose = prompt("Choose a number from 1-10. If you choose the same number as the computer, you win!");
    func2(userChoose);
};

var func2 = function(userChoose ) {
    computerChoose = Math.random();
    computerChoose = Math.round(computerChoose*10)/10;
    if (userChoose === computerChoose) {
        console.log("You won! The computer chose the number " + userChoice + " just like you! Good job!");
    } else if (userChoose > 10) {
        console.log("I'm sorry, you wrote something above 10. Try again.");
    } else {
        console.log("Sorry! The computer got " + computerChoose + 
        " and you got " + userChoose + ". Sorry!");
    }
};

func1();

デモはこちら

于 2013-10-05T20:22:41.873 に答える