75
rated 0 times
[
77]
[
2]
/ answers: 1 / hits: 40334
/ 13 Years ago, wed, march 16, 2011, 12:00:00
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.
More From » arrays