Reputation: 139
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
Upvotes: 1
Views: 155
Reputation: 8280
I could be wrong, but I think it's due to the fact that bar
is returning a reference to a property within an object. Changing your selectors to foo[bar][0]
works a treat.
foo = [['3','4'],['5','6']];
for (bar in foo) {
alert(foo[bar][0]);
alert(foo[bar][1]);
}
In cases where your object is simply a multi-dimensional array, I would sway array from using the for in
statement, as it can select unwanted properties. I would stick to the good old fashioned for(start, stop, increment)
foo = [['3','4'],['5','6']];
for (i = 0; i < foo.length; i++) {
alert(foo[i][0]);
alert(foo[i][1]);
}
As there has been mention of jQuery's .each
method I thought I'd also post an example of how it could be utilised. The jQuery's each method passes 2 optional parameters, indexInArray
, and valueOfElement
. Additionally, the jQuery documentation also states that
The value can also be accessed through the
this
keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value
With this in mind, we could achieve the same results as previous example, using the following jQuery (jsFiddle):
var foo = [['3','4'],['5','6']];
$.each(foo, function() {
// 'this' is the context of the current item within the array
alert(this[0]);
alert(this[1]);
})
Upvotes: 1
Reputation: 413818
The JavaScript for ... in
loop gives you the names of the object properties, not the values.
Don't use for ... in
for real arrays. Use a numeric index or .forEach()
.
The reason you're getting your output is complicated and uninteresting, since you just shouldn't do that, but here's a start. The property names will be coerced to strings by the for ... in
. Thus, on the first iteration, "bar" is the string "0", so ("0")[0]
is just "0", and ("0")[1]
is undefined
because "bar" is a single-character string.
After that, your for ... in
loop staggers into some other properties inherited from somewhere; perhaps you're using Prototype or something. The loop then alerts the first two characters of the names of all those other properties.
Upvotes: 6