Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

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

  • 14-04-2014 02: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, Registered Users 2 Posts: 2,011 ✭✭✭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