[英]How do I define a global variable in a function that can be accessed by other functions (JavaScript)?
The user is passing a value to a function and I'm trying to assign that value to a global variable but can't figure out how to do it. 用户正在将值传递给函数,而我试图将该值分配给全局变量,但无法弄清楚该怎么做。
var a;
function changeValue(newValue) {
a = newValue;
}
alert("Value of 'a' outside the function " + a); //I want this to output the value of newValue
Your function works fine, you simply need to call it: 您的函数运行正常,您只需要调用它即可:
var a;
function changeValue(newValue) {
a = newValue;
}
changeValue(100); // Function call changes the value of a to 100
alert("Value of 'a' outside the function " + a); // 100
Here you are: 这个给你:
var a;
b = 0;
function changeValue(newValue) {
a = newValue;
b = newValue;
}
changeValue('a');
changeValue('b');
alert("Value of 'a' outside the function " + a);
alert("Value of 'b' outside the function " + b);
Hope this help. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.