Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么此javascript数组打印出0?_Javascript_Arrays_List_Canvas - Fatal编程技术网

为什么此javascript数组打印出0?

为什么此javascript数组打印出0?,javascript,arrays,list,canvas,Javascript,Arrays,List,Canvas,我有一个名为front images的数组,写为var frontImages=[];。据我所知,javascript数组不需要指定长度。当我运行下面的代码时,当输出到控制台时,它会打印0作为数组的长度。但是,当我将数组长度指定为var frontImages=new Array3;,它打印出3,数组的正确长度。为什么未指定长度的数组不返回3 function getMainPosters() { var games = new Image(); //create 3 images

我有一个名为front images的数组,写为var frontImages=[];。据我所知,javascript数组不需要指定长度。当我运行下面的代码时,当输出到控制台时,它会打印0作为数组的长度。但是,当我将数组长度指定为var frontImages=new Array3;,它打印出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

}

映像是异步加载的,因此在运行console.log时,frontImages的长度仍然是0


您需要等待要加载的图像,然后才能使用jQuery Deferred或其他一些自定义构造来查询任何信息

在执行onload函数之前,您正在将数组打印到控制台,此时数组为空,由于您等待的映像尚未加载?

在onload处理程序中放入一些console.log,这一点变得非常明显。