How does javascript foreach work with multidimensional arrays?

I played a bit with javascript and found out (at least for me) strange behavior when working with multidimensional arrays through a foreach 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> 

Output:

 First: 0 undefined 1 undefined Second: abcd 

I would expect the first and second to be the same. Could you explain to me what I am missing?

Note. Please do not advise iterating over the array through jQuery or otherwise. I have no problems with coding, I'm just interested to know about this particular situation. Thanks!

+4
source share
3 answers

It was wonderful that Eric Mikelsen pointed out, but so summed up.

  • for (... in ...) loop repeats through the properties of the object
  • array Is an object in Javascript, so you can iterate over an array with it. But it will be slower and not recommended at all (see why this is).
  • The fact that it iterates over properties, not values, means that it returns indexes, not array values ​​(this can be convenient when you have associative arrays)
  • An example in the question can be resolved using for (... in ...) loop

in the following way:

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

In the example of an associative array, the for (... in ...) loop will be convenient:

 var person = []; person["id"] = 1; person["born"] = 2009; person["favourite_meal"] = "chicken"; var fourth = ''; for (var arrayIndex in person) { fourth += ' ' + person[arrayIndex]; } 
+7
source

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

+1
source

I use this dump () function all the time to debug my multidimensional arrays.

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

If you have questions about its implementation, let me know.

0
source

Source: https://habr.com/ru/post/1343973/


All Articles