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!
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!
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.
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
}
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);
}
}