gpt4 book ai didi

Javascript:函数内的全局变量

转载 作者:行者123 更新时间:2023-12-02 18:16:53 24 4
gpt4 key购买 nike

所以我有以下代码:

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

演示 here

关于Javascript:函数内的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19202316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com