我有一个名为var frontImages = [];
的前图片。从我所了解的JavaScript数组不需要指定的长度。当我运行下面的代码时,当输出到控制台时,它将输出0作为数组的长度。但是,当我将数组长度指定为var frontImages = new Array(3);
时,它会输出3,这是数组的正确长度。为什么没有指定长度的数组返回3?为什么这个javascript数组打印出0?
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
}
在'onload'处理程序中加入一些'console.log',它变得非常明显。 – 2013-02-20 21:08:04