Home > Back-end >  [JavaScript]Add elements to a global array in a function and keep them
[JavaScript]Add elements to a global array in a function and keep them

Time:02-13

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?

CodePudding user response:

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.

CodePudding user response:

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

Note that :

window. onl oad() 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

}

CodePudding user response:

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);
  }
}

CodePudding user response:

The code is right, you're getting an error because the browser is running func1() before the list array is rendered in. Just move it before window.onload() and you're good.

const list = [];

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

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

console.log(list);

  • Related