Javascript:函数内部变量的全局化

Javascript:函数内部变量的全局化,javascript,function,variables,globalization,Javascript,Function,Variables,Globalization,因此,我有以下代码: 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 =

因此,我有以下代码:

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

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


多谢各位

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

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