问题
I have an array called front images written as var frontImages = [];. From what I understand javascript arrays don't need a specified length. When I run the code below, it prints 0 as the length of the array when output to the console. However, when I specify the array length as var frontImages = new Array(3);, it prints out 3, the correct length of the array. Why doesn't the array with the unspecified length return 3?
function getMainPosters() {
var games = new Image(); //create 3 images
var apps = new Image();
var aboutme = new Image();
games.onload = function() { //add image to frontImages array on load
frontImages.push(games);
};
apps.onload = function() {
frontImages.push(apps);
};
aboutme.onload = function() {
frontImages.push(aboutme);
};
games.src = "images/assets/posters/games_poster.jpg"; //specify source of image
apps.src = "images/assets/posters/apps_poster.jpg";
aboutme.src = "images/assets/posters/aboutme_poster.jpg";
console.log(frontImages.length); //print the length of frontImages to console
}
回答1:
You're printing the array to the console before the onload functions have executed, and at that time the array is empty, as the images you are waiting for has'nt loaded yet ?
回答2:
The images are being loaded asynchronously, so by the time console.log gets run, the length of the frontImages is still 0.
You need to wait on the images to load before you can query any information against them (either by using jQuery Deferred or some other custom construct)
来源:https://stackoverflow.com/questions/14989827/why-does-this-javascript-array-print-out-0