为什么有些函数可以识别这个全局变量而其他函数却不能?

Why do some functions recognize this global variable but others don't?

所以我有以下 JS 函数,它根据全局列表 events 添加行到 table。事件一开始是空的,我有另一个函数将 dict 对象推入其中。项目已成功推送到列表,但是,当 events 达到 fillTable() 时,它是空的。在下面的代码中,第一个 console.log(events)(在 fillTable() 内)打印一个空列表,但第二个 console.log(events) 按预期打印数据。 events 没有在其他任何地方定义,所以我迷路了。

events = []

function otherFunction(repo, type, url) {
    events.push({'repo': repo, 'type': type, 'url': url})
}

function fillTable() {

    console.log(events);         // {}
    console.log(events.length);  // 0

    var table = document.getElementById("table")
    for (let i = 0; i < events.length; i++) {
        let event = events[i];

        const repo = document.createElement('td')
        repo.appendChild(document.createTextNode(event['repo']));

        const type = document.createElement('td')
        type.appendChild(document.createTextNode(event['type']));
        
        const url = document.createElement('td')
        url.appendChild(document.createTextNode(event['url']));

        const row = document.createElement('tr')
        row.appendChild(repo);
        row.appendChild(type);
        row.appendChild(url);
        table.appendChild(row);
    }
}

otherFunction('a', 'b', 'c');
console.log(events);         // {'repo': 'a', 'type': 'b', 'url': 'c'}
console.log(events.length);  // 1

fillTable();

这是您使用异步函数的问题。

events = []
getGithubActivity();//this function makes an xmlHttp request
fillTable();//this function is called straight after. There has been no chance for a return of the xmlHttp request.

我建议像这样放置 fillTable

request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
            try {
                //add events
               fillTable();
            }
            catch (e) {
                console.log('getGithubActivity() - Error: ' + e);
            }
        }
    };

当您在控制台中记录对象时。它会在打开时更新,这就是为什么它在您看来已填充,即使在记录时长度为 0。当您在控制台中打开它时,请求已返回。

我还注意到 eventList 没有在任何地方定义,这可能是一个错字吗?