简体   繁体   English

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

[英]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.

相关问题 如何在JavaScript中定义可在所有函数中访问的全局变量 - How to define a global variable in JavaScript that can be accessed in all the functions 如何在javascript函数内部定义全局变量并在其外部访问它? - How can I define a global variable inside javascript function and access it outside it? 如何更好地在面向对象的javascript函数中定义全局变量 - How can I define a global variable in object-oriented javascript function better 如何在JavaScript中的多个函数中使用Global变量? - How can I use Global variable across multiple functions in JavaScript? 无法在函数内部访问JavaScript全局变量 - JavaScript Global Variable cannot be accessed inside function 如何将javascript函数定义为变量中的变量 - How do I define a javascript function as a variable from a variable 在 JavaScript 函数中定义全局变量 - Define a global variable in a JavaScript function 我可以在函数内定义一个javascript变量(不是全局变量),并且该变量在其作用域内是可见的吗? - Can I define a javascript variable (not global) inside a function and this variable be visible ouside his scope? 如何在javascript中定义全局变量 - how to define global variable in javascript 在哪里初始化 JavaScript 中许多函数将访问的全局变量 - Where to initialize the global variable that will be accessed by many functions in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM