0

In the below JavaScript code :-

var a  = [];
for (i in a) {
  alert(i);

}

I am getting o/p as - $family, $constuctor, each, clone, clean, invoke, associate, link, contains, append, getlast, getRandom, include, combine, erase, empty, flatten, pick, hexToRgb, rgbToHex.

Can anybody explain why is that so?Has it got to do something with properties of Array objects and if so then why aren't all the properties alerted? Also , if we take a empty object literal like var a = {} , we don't get any o/p.

Now , if I change the above code like :-

var a  = [9,2];
for (i in a) {
    if (a.hasOwnProperty(i)) {
        alert(a.hasOwnProperty(i));
        alert(i);
      }
} 

I get the output as 0 and 1.Why is that so ? Are those the properties of this Array object (which are also the indexes) ?

Rohit P
  • 337
  • 3
  • 12

1 Answers1

3

The for-in syntax is for objects. It iterates all fields of the object, including methods. When you want to iterate an array, always use this:

for (var i = 0; i < array.size; i++) {
    doSomething(array[i]);
}

Your latter loop with hasOwnProperty doesn't iterate over the standard methods of arrays, because your array a inherited these methods from the base Array class, so they aren't it's own properties. But when you explicitely add a method to an array, it should also list the function because it is now an own property:

var a  = [9,2];
a.hello = function() { };

for (i in a) {
    if (a.hasOwnProperty(i)) {
        alert(a.hasOwnProperty(i));
        alert(i);
      }
} 

This should list 0, 1 and hello.

In case you expected it to output 9 and 2 and you wonder why it outputs 0 and 1: That's because the for-in array iterates over the keys, not over the values. And arrays are basically objects where each array element is a property with the array index as a name. So

var a = [9, 2];

is equivalent to this object (plus the stuff inherited from Array):

var a = {
    0: 9,
    1: 2
}
Philipp
  • 67,764
  • 9
  • 118
  • 153
  • -@Philipp ..Thanks...if thats the case then why arent all properties of Object inherited if we write - var x = {a:10 , b:20} and then when we iterate over its properties we see only 10 and 20 ? – Rohit P Oct 02 '12 at 18:15
  • Because the basic Object has no properties. – Philipp Oct 02 '12 at 21:14