JavaScript Multidimensional Arrays [duplicate]

JavaScript does not have multidimensional arrays, but arrays of arrays, which can be used in a similar way.

You may want to try the following:

var photos = [];
var a = 0;
$("#photos img").each(function(i) {
    photos[a] = [];
    photos[a]["url"] = this.src;
    photos[a]["caption"] = this.alt;
    photos[a]["background"] = this.css('background-color');
    a++;
});

Note that you could have used new Array() instead of [], but the latter is generally recommended. Also note that you were missing the parenthesis of new Array() in the first line.


UPDATE: Following from the comments below, in the above example there was no need to use arrays of arrays. An array of objects would have been more appropriate. The code is still valid because arrays are objects in this language, but the following would have been better:

photos[a] = {};
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');

Leave a Comment