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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With