簡體   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