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

277
Visualizações
[JavaScript]Add elements to a global array in a function and keep them

window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Your function's code is fine.

However, you are logging the array using console.log before func1() gets to run, since window.onload fires AFTER everything has loaded.

about 4 years ago · Juan Pablo Isaza Relatório

0

Let's focus on why the console.log in the end is empty.

Note that :

window. onload() is invoked when all resources (the document, objects, images, css, etc) have finished rendering.

So after the console output the list value, if will execute the func1 and assign the value to list, but before that list is just an empty array.

If could see the following snippet, if you put the console to the window.onload function, it works as epected.

You could use push to add item to array and use index to access a specific element.

window.onload = function(){
    func1();
    console.log(list);
    func2()
    console.log(list)
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}
console.log(list);
function func2(){
list[0] =9999

}

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to wait for the window to load and call your function func1 before logging the value of the array to console...

window.onload = function(){
    func1();
    console.log(list);
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

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