簡體   English   中英

全局變量在函數中分配值時未更新

[英]Global variable not updating when I assign it a value within a function

我正在嘗試使用jQuery在.txt文件中基於離線創建數組。 該數組是游戲答案的列表。

控制台第一次記錄的是內容數組,而第二次記錄的是空數組。 為什么answers無法在全球范圍內更新?

這是我的代碼:

//create global variable answers
var answers = new Array;
//assign a value to answers from text file
$.get("wordsEn.txt", function(txt){
    answers = txt.split('\n');
    console.log(answers);
});
console.log(answers);

console.log(answers); 回調之外發生分配之前

$.get立即返回,但是它的回調不一定立即運行; 可能需要一段時間才能獲取數據。 同時,外部console.log(answers); 運行。

您需要在現場調用一個函數,例如

    //create global variable answers
var answers = new Array;
var cb = function(){
    console.log(answers);
};
//assign a value to answers from text file
$.get("wordsEn.txt", function(txt){
    answers = txt.split('\n');
    console.log(answers);
    if(cb)
        cb();
});

您有兩個console.log調用,所以一個問題是您不知道哪個首先發生,因為一個同步發生,而另一個則異步發生。 對於初學者,如果您要像這樣調試,則應在日志語句中添加一些其他信息:

console.log('1: ' + answers);
console.log('2: ' + answers);

這樣,當您看到輸出時,您將知道2首先發生還是1首先發生。

就像其他人所說的那樣, $.get代碼中使用的內部函數是異步發生的,這意味着它將在ajax請求完成運行,有時您可能會很快或很慢,您無法知道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM