0

I create a javaScript gallery where the document can handle a variable number of <div class="gallery"> elements. I thought to define a multi-dimensional array which stores information for every existing galery.

JavaScript + jQuery 1.9.1

var gallery = new Array;
gallery = ['images','imageActive','width'];

for (var i=0;i<$('.gallery').length;i++) {
    gallery[i]['images'] = $('.gallery:eq['+i+'] img').index();
    gallery[i]['imageActive'] = 0;
    gallery[i]['width'] = $('.gallery:eq['+i+'] li').css('width');
}


Console output

enter image description here

Is my approach totally wrong? Are arrays not intended for this case?

Tomkay
  • 5,120
  • 21
  • 60
  • 92

3 Answers3

2

assign to object {}

for (var i=0;i<$('.gallery').length;i++) {
   gallery[i] = {};
   gallery[i]['images'] = $('.gallery:eq['+i+'] img').index();
rab
  • 4,134
  • 1
  • 29
  • 42
0

gallery = new Array will create an empty array. You need to fill your array with objects first before accessing any properties:

var gallery = [];
gallery = ['images','imageActive','width'];

for (var i=0;i<$('.gallery').length;i++) {
    gallery.push({}); // increase length and add empty object

    gallery[i]['images'] = $('.gallery:eq['+i+'] img').index();
    gallery[i]['imageActive'] = 0;
    gallery[i]['width'] = $('.gallery:eq['+i+'] li').css('width');
}
Zeta
  • 103,620
  • 13
  • 194
  • 236
0

First off, your first assignment (= new Array) is completely unnecessary, you're overwriting it with the next line, where you're creating an array with literal syntax.

I think you meant this:

var gallery = [];
for (var i=0;i<$('.gallery').length;i++) {
    gallery[i] = {
        images:      $('.gallery:eq['+i+'] img').index(),
        imageActive: 0,
        width:       $('.gallery:eq['+i+'] li').css('width')
    };
}

That creates a blank array, then puts entries in it, where each entry is an object (or "map" or "dictionary," we don't use the term "associative array" in JavaScript to avoid confusion with, well, arrays). Each object has the images, imageActive, and width properties.

BTW, there may be a more efficient way to write that:

var gallery = $(".gallery").map(function() {
    var entry = $(this);
    return {
        images:      entry.find('img').index(),
        imageActive: 0,
        width:       entry.find('li').css('width')
    };
}).get();

That uses map to loop through the elements and build the array, which is returned initially as a jQuery object, and so we use get to get the underlying actual array.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875