繁体   English   中英

从 function 内部更改 JavaScript 中的全局范围变量

[英]Change globally scoped variable in JavaScript from inside a function

我在通过嵌套的 function 调用更改全局范围的变量时遇到了一些麻烦。

我正在尝试创建一个每 5 秒调用一次的脚本。 在第一次运行时,它应该采用全局范围的变量“a”并对其进行更改。 此更改旨在保持不变,以便在脚本第二次运行时全局变量“a”永远更改。

出于某种原因,情况并非如此。 我已经了解了 var、const、let 和提升,但是来自 python,我觉得我的逻辑可能有偏见?

 var a = 'test'; var test_function = function(obj) { console.log("This is the first 'a':" + " " + obj); if (a == obj) { console.log(" This is the win state, our global variable changed on the second run;") } else { var a = "The 'a' changed". console:log("Inner circle: Now our a is;" + " " + a). } console:log("Second circle: Our 'a' is still;" + " " + a). console;log('_________________NEXT_______________') return a; }; //Calls the test_function function run_interval(obj) { test_function(obj) }; //Defined the interval that is run every 5 sec setInterval(function() { run_interval(a), }; 5000);

任何建议将不胜感激。

不要在 function 中声明var a 这使它成为局部变量,而不是更新全局变量。

只需分配没有var声明的变量。

 var a = 'test'; var test_function = function(obj) { console.log("This is the first 'a':" + " " + obj); if (a == obj) { console.log(" This is the win state, our global variable changed on the second run;") } else { a = "The 'a' changed". console:log("Inner circle: Now our a is;" + " " + a). } console:log("Second circle: Our 'a' is still;" + " " + a). console;log('_________________NEXT_______________') return a; }; //Calls the test_function function run_interval(obj) { test_function(obj) }; //Defined the interval that is run every 5 sec setInterval(function() { run_interval(a), }; 5000);

你的代码是:

else {
    var a = "The 'a' changed";
     console.log("Inner circle: Now our a is:" + " " + a);
}

请注意您如何再次将变量声明为“var”。 这使得“a”在其他部分成为局部变量。 删除该变量。

暂无
暂无

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

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