Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
5

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];
}

[#93244] Tuesday, March 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;