-6

Here I have variable that has an object whose one value is an array of objects eg.

var test = { "key1": val1,
"key2": [{"a":1,
        "b":[{},{}]
        },
        {"a":1,
        "b":[{},{}]
        }]
   };    

I am now unable to understand why following piece of code iterates two times. Shouldnt it just iterate once as only 1 array element is present?

code snippet:

for( index in test.key2)
Pointy
  • 405,095
  • 59
  • 585
  • 614
Rusheel Jain
  • 843
  • 6
  • 20
  • 2
    is this some kind of a joke or something ? – jAndy Feb 16 '15 at 16:08
  • 2
    There are definitely two elements: the first is `{"a":1, "b": [{},{}]}` and the second is the same as that. Does your question have something to do with the fact that the two elements look the same? – Pointy Feb 16 '15 at 16:08
  • `key2` is an array with two items. But don't use for/in for arrays. In Javascript you should use the index numbers to iterate over an array. for/in is for objects. See "Why is using “for…in” with array iteration such a bad idea?" http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – Mörre Feb 16 '15 at 16:12

2 Answers2

4

This is where good indentation is key.

var test = {
    "key1": val1,
    "key2": [
        {
            "a":1,
            "b":[{},{}]
        },
        {
            "a":1,
            "b":[{},{}]
        }
    ]
};

Here you can clearly see that it in fact has 2 items.

SeinopSys
  • 8,787
  • 10
  • 62
  • 110
0

Because test.key2 is a array having two elements, So it will iterate two times.

Check test.key2.length;

void
  • 36,090
  • 8
  • 62
  • 107