Así que tengo la siguiente función JS que agrega filas a una tabla en función de una lista global, events . Los eventos comienzan vacíos y tengo otra función que inserta el objeto dict en él. Los elementos se envían a la lista con éxito; sin embargo, cuando events llegan a fillTable() , está vacío. En el siguiente código, el primer console.log(events) (dentro fillTable() ), imprime una lista vacía pero el segundo console.log(events) imprime los datos como se esperaba. events no se definen en ningún otro lugar, así que estoy perdido.
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();Este es un problema con su uso de funciones asíncronas.
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.sugiero colocar fillTable como este
request.onreadystatechange = function () { if (request.readyState == 4 && request.status == 200) { try { //add events fillTable(); } catch (e) { console.log('getGithubActivity() - Error: ' + e); } } };Cuando registra un objeto en console. Se actualizará al abrirlo, es por eso que aparece lleno, aunque en el momento del registro la longitud era 0. Para cuando lo abre en la consola, la solicitud ha regresado.
También noté que eventList no está definido en ninguna parte, ¿podría ser esto un error tipográfico?