【问题标题】:Javascript: Globalizing variables inside functionJavascript:在函数内全球化变量
【发布时间】:2013-10-05 20:21:06
【问题描述】:

所以我有以下代码:

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。”,即使我放了 3 个。

如果我错了,请纠正我,但我相信这是因为我试图更改函数内部的变量。我的主要问题是如何将函数内部的变量全球化,以便在不同的函数中使用和修改?

谢谢。

【问题讨论】:

    标签: javascript function variables globalization


    【解决方案1】:

    您可以在调用函数时传递值。试试这个:

    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();
    

    演示here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多