6

I was playing a bit with JavaScript and found out (at least for me) strange behaviour when dealing with multi-dimensional arrays via a for...in loop. So I have this piece of code:

<script type="text/javascript">
  var arr = [['a', 'b'], ['c','d']];

  var first='';

  for (var singleArray in arr) {
    first += ' ' + singleArray[0] + ' ' + singleArray[1];
  }

  var second = '';
  for (var i=0;i<arr.length; i++) {
    second += ' ' + arr[i][0] + ' ' + arr[i][1];
  }

  console.log('First: ', first);
  console.log('Second: ', second);
</script>

The output is:

First: 0 undefined 1 undefined
Second: a b c d

I would expect the first and second will be the same. Can you please explain me what I am missing?

Note: please do not advise to iterate over the array via jQuery or somehow else. I don't have coding troubles, I am just curious about this particular situation.

2
  • 1
    It should not be titled forEach when it does not use forEach. For e.g. this : arr.forEach(function(is) { is.forEach( function (his) { console.log(his) } ) } ); does the right thing. Commented Mar 17, 2013 at 10:31
  • @CrisStringfellow I also found the question's title to be misleading, since I was looking for information about the forEach loop. What should this question's title be, then? Commented Jul 20, 2013 at 22:34

3 Answers 3

10

There were some good point from Erick Mickelsen pointed out but so sum it up.

  1. for (... in ...) loop iterates over object properties
  2. array IS an object in Javascript so you may iterate over an array with it. But it will be slower and it is generaly not recommended (see why is that)
  3. The fact that it iterates over properties rather than values means, that it returns indexes rather than array values (this may be handy when you have associative arrays)
  4. The example in the question may be solved with for (... in ...) loop

as follows:

var third = '';
for (var arrayIndex in arr) {
  third += ' ' + arr[arrayIndex][0] + ' ' + arr[arrayIndex][1];
}

In the associative array example the for (... in ...) loop will be handy:

var person = [];
person["id"] = 1;
person["born"] = 2009;
person["favourite_meal"] = "chicken"; 

var fourth = '';
for (var arrayIndex in person) {
  fourth += ' ' + person[arrayIndex];
}
Sign up to request clarification or add additional context in comments.

1 Comment

In JavaScript, the term "associative array" is not used. What your second example shows is the fact that arrays are objects in addition to being arrays, and that for...in iterates over keys. It would be better to use var person = {}; on the first line, as you say in point #2.
1

for (... in ...) iterates over the properties of an object, not the elements of an array. w3schools, javascript garden

4 Comments

Hm, but I saw it several times and validated myself that for (... in ...) works on arrays with single dimension. This is by chance?
@Jan: It will work for arrays but it still iterates over the property names/indexes, not the values. Be careful with that though, because it iterates over all properties, not just the indexes, including functions added to Array.prototype. JavaScript's for/in really isn't designed for arrays, it just happens to work (sort of).
Just found somewhere that it works quite OK with arrays, but the difference here is that it doesn't return values but indexes instead ...
Eric, can you link to a different resource besides w3schools? Mention of for(...in...) without mentioning hasOwnProperty is harmful. bonsaiden.github.com/JavaScript-Garden/#object.forinloop
0

I use this dump() function all the time to debug my multi-dimensional arrays.

http://binnyva.blogspot.com/2005/10/dump-function-javascript-equivalent-of.html

If you have questions about implementing it, let me know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.