2013-02-20 49 views
0

我有一个名为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 

} 
+0

在'onload'处理程序中加入一些'console.log',它变得非常明显。 – 2013-02-20 21:08:04

回答

4

在onload函数执行之前,您正在将数组打印到控制台,并且当时数组为空,因为您的图像等待还没装过吗?

+0

哇。这应该是显而易见的,谢谢。 – kag359six 2013-02-20 21:19:59

4

的图像正在异步加载,因此受到时间的console.log被运行时,frontImages的长度仍为0

你需要等待图像加载之前就可以查询任何关于他们的信息(通过使用jQuery Deferred或其他一些自定义构造)