繁体   English   中英

如何在一个可以被其他函数(JavaScript)访问的函数中定义全局变量?

[英]How do I define a global variable in a function that can be accessed by other functions (JavaScript)?

用户正在将值传递给函数,而我试图将该值分配给全局变量,但无法弄清楚该怎么做。

var a;    

function changeValue(newValue)    {
     a = newValue;
}

alert("Value of 'a' outside the function " + a); //I want this to output the value of newValue

您的函数运行正常,您只需要调用它即可:

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

这个给你:

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

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM