I have an odd problem. I’m trying to use Javascript to fetch me some values from a multidimensional array, and it’s giving me some weird output.
Here is my code:
foo = [['3','4'],['5','6']];
for (bar in foo) {
baz = bar[0];
alert(baz);
qux = bar[1];
alert(qux);
}
Here is the output of the above:
// These are all alerts, by the way
0,undefined,1,undefined,$,f,$,c,e,a,c,l,c,l,i,i,n,a,s,l,i,c,o,a,p,g,e,g,e,i,n,c,o,e,r,e,m,f,l,p,i,h,e,r,g
Can somebody tell me what is happening?
Here is a jsFiddle of the problem: http://jsfiddle.net/Jey6w/
Edit:
Here is another jsFiddle, with another layer of “Inception”: http://jsfiddle.net/8vyGq/
The output:
// Again, these are all alerts, and * signifies undefined
0**1**$ff$ceaacllcllinnassliicooappgeegeeinncooerremmfllpiiheergg
I could be wrong, but I think it’s due to the fact that
baris returning a reference to a property within an object. Changing your selectors tofoo[bar][0]works a treat.In cases where your object is simply a multi-dimensional array, I would sway array from using the
for instatement, as it can select unwanted properties. I would stick to the good old fashionedfor(start, stop, increment)Update – jQuery
As there has been mention of jQuery’s
.eachmethod I thought I’d also post an example of how it could be utilised. The jQuery’s each method passes 2 optional parameters,indexInArray, andvalueOfElement. Additionally, the jQuery documentation also states thatWith this in mind, we could achieve the same results as previous example, using the following jQuery (jsFiddle):