Javascript:在函数中全球化变量
Javascript: Globalizing variables inside function
所以我有以下代码:
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();
在这里演示
相关文章:
- 将函数的上下文应用于javascript变量
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- 将PHP变量传递给jQuery时遇到问题
- 如何通过ajax刷新JSF填充的javascript变量
- 参数变量出现ngTable指令问题
- 通过javascript重定向html传递php变量
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- 全局变量和全局对象的属性之间有什么区别吗
- 如何在Bootstrap Modal中为动态点击生成的变量设置jade属性
- 值对象在某个变量发生更改后发生更改
- Javascript变量赋值|
- AngularJS-在JSON选择器中使用变量名
- Javascript计数器变量未显示正确的值
- delete关键字在全局变量上的不同行为
- 如何在php变量中嵌入JQuery代码
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- Javascript:在函数中全球化变量
- javascript:如何从闭包全球化变量
- 在JavaScript中快速全球化许多变量的方法