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!
source share