Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi all,
Vanilla are planning an update to the site on April 24th (next Wednesday). It is a major PHP8 update which is expected to boost performance across the site. The site will be down from 7pm and it is expected to take about an hour to complete. We appreciate your patience during the update.
Thanks all.

[JS] Push to multidimensional array, first element empty?

  • 14-04-2014 3:08pm
    #1
    Closed Accounts Posts: 4,763 ✭✭✭


    On page load, I take a list of every image in each gallery element on the page, and push this to a temporary array. I then push this temporary array to a multidimensional array of all such gallery elements on the page.

    However, the first element in the array comes up with a length of 0, and appears empty so far as I can tell. The arrays are getting pushed to indexes 1, 2, 3, etc., instead of 0, 1, 2.
    var galleryImages = [[]];
    
    $(window).load(function() {
        $('.' + galleryClass).each(function() { 
            var tmp = [];
    
            $(this).children('img').each(function() {
                tmp.push(this);
            });
    
            galImg.push(tmp);
        });
    });
    

    On this given page there are four galleries:

    The first has 16 images.
    The second has 15 images.
    The third has 18 images.
    The fourth has 34 images.

    This is what I see when I output lengths:
    $(galleryImages).each(function(index, element) {
        console.log('galleryImages[' + index + '].length: ' + element.length);
    });
    
    galleryImages[0].length: 0
    galleryImages[1].length: 16
    galleryImages[2].length: 15
    galleryImages[3].length: 18
    galleryImages[4].length: 34
    

    What glaringly obvious thing have I missed here?


Comments

  • Registered Users Posts: 2,030 ✭✭✭colm_c


    Most likely because when you declare
    var galleryImages = [[]];
    

    You're actually setting galleryImages to be an array with one item in it, an empty array.

    Just set it to empty (javascript doesn't care about multi dimensional arrays).
    var galleryImages = [];
    


  • Closed Accounts Posts: 4,763 ✭✭✭Fenster


    Ah, brilliant, that was it. I declared as I did because I was told it was the Correct Way to declare a multidimensional array. :)


Advertisement