Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
Why do some functions recognize this global variable but others don't?

So I have the following JS function that adds rows to a table based on a global list, events. Events starts out empty and I have another function pushing dict object into it. Items are pushed to the list successfully, however, when events reaches fillTable(), it's empty. In the code below, the first console.log(events) (inside fillTable()), prints an empty list but the second console.log(events) prints the data as expected. events isn't being defined anywhere else so I am lost.

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();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is a problem with your usage of async functions.

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.

i suggest placing fillTable like this

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

When you log an object in console. It will update upon being opened, this is why it appears filled to you even though at the time of logging the length was 0. By the time you open it in console, the request has returned.

Also I noticed that eventList isn't defined anywhere, could this possibly be a typo?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda