【问题标题】:Why does this javascript array print out 0?为什么这个javascript数组打印出0?
【发布时间】:2013-02-06 01:02:06
【问题描述】:

我有一个名为front images 的数组,写成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

}

【问题讨论】:

  • 将一些console.logs 放在onload 处理程序中,就变得非常明显了。

标签: javascript arrays list canvas


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    图片是异步加载的,所以当console.log运行时,frontImages的长度还是0。

    您需要等待图像加载完毕,然后才能针对它们查询任何信息(使用 jQuery Deferred 或其他一些自定义构造)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多