-2
Object.prototype.jack = {};

var a = [1,2,3];

for(var number in a){
    alert(number);
}

Could anyone tell me why the word "jack" jumped out of the alert box?

Thank you very much!

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
  • 1
    [hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty), but you should be using a regular `for` loop... – elclanrs Aug 20 '13 at 00:57
  • 2
    Because `jack` is an enumerable property and you are iterating over all properties of `a`. Related: [Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/q/500504/218196) – Felix Kling Aug 20 '13 at 01:01

3 Answers3

5

Simple - arrays are objects in javascript so by adding:

Object.prototype.jack={};

You've added an enumerable property 'jack' to all objects (and by that to all arrays).

once creating your array "a" and looping through all of its properties

for(var number in a)

You are sure to get a 'jack' alert. To avoid it showing up you can use .hasOwnProperty() to make sure all alerted properties are not inherited. or use a regular

for(var i=0; i < a.length; i++)

loop.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
3

The for..in loop iterates over properties. It's only recommended (by Mozilla and other authorities) to be used on Objects, but not Arrays. If you insist, this is the correct way to iterate over an object and it will work for an array (most of the time).

for (var number in a) {
    if (Object.prototype.hasOwnProperty.call(a, number)) {
        alert(a[number]); // shows 1 then 2 then 3
    }
}

To do it the generally accepted way,

for (var i=0; i<a.length; i++) {
    alert(a[i]);  // same as above
}

My personal preference is:

for (var val, i=0; val = a[i]; i++) {
    alert(val);  // same as above
}
Brigand
  • 84,529
  • 20
  • 165
  • 173
0

Because you're not checking if jack is a property inherited from prototype or not. Try this instead:

Object.prototype.jack={};

var a = [1,2,3];

for (var number in a) {
    if (a.hasOwnProperty(number)) {
        alert(number);
    }
}
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67