所以我有以下 JS 函式,它根據全域串列將行添加到表中,events. 事件開始時為空,我有另一個函式將 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();
uj5u.com熱心網友回復:
這是您使用異步函式的問題。
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 沒有在任何地方定義,這可能是一個錯字嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375218.html
標籤:javascript 数组 dom 全局变量 全球的
