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.
There were some good point from Erick Mickelsen pointed out but so sum it up.
for (... in ...)
loop iterates over object propertiesarray
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)for (... in ...)
loopas 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];
}
for (... in ...)
iterates over the properties of an object, not the elements of an array. w3schools, javascript garden
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With