Saturday, December 1, 2018

jquery - JavaScript Multidimensional Arrays





This wasn't the question I was going to ask but I have unexpectedly run aground with JavaScript arrays. I come from a PHP background and after looking at a few websites I am none the wiser.



I am trying to create a multi-dimensional array.



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

a++;
});


Error message: photos[a] is undefined. How do I do this? Thanks.


Answer



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');

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...