[英]How to define a global variable in JavaScript that can be accessed in all the functions
[英]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.