0

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

}
1
  • Put some console.logs in the onload handlers, and it becomes very obvious. Commented Feb 20, 2013 at 21:08

2 Answers 2

4

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 ?

Sign up to request clarification or add additional context in comments.

Comments

4

The images are being loaded asynchronously, so by the time console.log gets run, the length of the frontImages is still 0.

You need to wait on the images to load before you can query any information against them (either by using jQuery Deferred or some other custom construct)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.