为什么这个javascript数组打印出0?

时间:2013-02-20 21:01:07

标签: javascript arrays list canvas

我有一个名为前映像的数组,写为var frontImages = [];。根据我的理解,javascript数组不需要指定的长度。当我运行下面的代码时,它输出到控制台时输出0作为数组的长度。但是,当我将数组长度指定为var frontImages = new Array(3);时,它会输出3,即数组的正确长度。为什么具有未指定长度的数组不返回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

}

2 个答案:

答案 0 :(得分:4)

图像是异步加载的,所以当console.log运行时,frontImages的长度仍为0.

您需要等待图片加载才能查询任何信息(通过使用jQuery Deferred或其他一些自定义构造)

答案 1 :(得分:4)

你是在onload函数执行之前将数组打印到控制台,那时数组是空的,因为你正在等待的图像还没有加载?

相关问题