Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Multidimensional Arrays [duplicate]

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.

like image 801
JasonS Avatar asked May 11 '10 07:05

JasonS


People also ask

How do you find duplicate elements in a multidimensional array?

Turn the 2d array into a 1d array ( List<Integer> ), then loop through the 1d array counting the duplicates as you find them and removing them so you don't count them more than once.

How do you remove duplicates from a two dimensional array?

Remove Duplicate Values from Multidimensional Array:Step 1:First we will use serialize() funtion to serialize the array. Then use map with php inbuilt function. Step 2: use unserialize() function to make the serialized string into a PHP value.


1 Answers

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'); 
like image 78
Daniel Vassallo Avatar answered Oct 03 '22 07:10

Daniel Vassallo