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

标签 javascript arrays list canvas

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

}

最佳答案

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

关于javascript - 为什么这个 javascript 数组打印出 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14989827/

相关文章:

javascript - 从html中调用JavaScript代码有几种方式?

php - 映射数组并且不让 future 的开发人员搞砸的最佳方法是什么?

java - 将泛型 T 转换为 List<T>

Python-循环遍历未排序的数组时计算某一项的出现次数

javascript - 无法让 js fadeIn() 工作

javascript - jQuery Select Checkbox 当文本存在时,从打印中隐藏未选中的行

javascript - 内联显示表单元素

arrays - Numpy 数组内存管理

arrays - 确定 array2 是否是 array1 的子数组的最有效算法?

c# - 如何在 C# 中过滤包含对象的列表?