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

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

本文介绍了为什么这个javascript数组打印输出0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,称为前面的图像写为 var frontImages = []; 。从我明白的javascript数组不需要一个指定的长度。当我运行下面的代码,它输出0作为数组的长度输出到控制台。然而,当我指定数组长度为 var frontImages = new Array(3); ,它打印出3,数组的正确长度。为什么不指定长度的数组返回3?

I have an array called front images written as var frontImages = [];. From what I understand javascript arrays don't need a specified length. When I run the code below, it prints 0 as the length of the array when output to the console. However, when I specify the array length as var frontImages = new Array(3);, it prints out 3, the correct length of the array. Why doesn't the array with the unspecified length return 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函数之前将数组打印到控制台,当时数组为空,因为您正在等待的图片尚未加载?

You're printing the array to the console before the onload functions have executed, and at that time the array is empty, as the images you are waiting for has'nt loaded yet ?

这篇关于为什么这个javascript数组打印输出0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:38