简体   繁体   中英

Iterating on Javascript arrays with the “in” keyword

It seems that I don't understand the meaning of the in keyword in JavaScript.

Have a look at this code snippet ( http://jsfiddle.net/3LPZq/ ):

var x = [1,2]
for(i in x){
    document.write(x[i]);
}

When run in the jsfiddle, it prints not only the values contained in the array, but also all of the array object's properties and methods.

When I change it like this ( http://jsfiddle.net/4abmt/ ):

$(document).ready(function(){
var x = [1,2]
for(i in x){
    document.write(x[i]);
}});

it prints only the values 1 and 2.

Why does this happen? Is this caused by jQuery or does the behavior of the in keyword depend on whether the document is fully loaded or not?

This happens because of prototype inheritance. An object doesn't only show its' own properties, but all of its' ancestors properties as well.

To find only an object's own properties, use obj.hasOwnProperty(prop) .

var x = [1,2];
for (var i in x) {
   if (x.hasOwnProperty(i)) {
       document.write(x[i]);
   }
}

See MDN Docs on hasOwnProperty .

Some of the libraries loaded by jsFiddle extend the default prototype of Array, thus it shows these extra functions. jQuery doesn't extend the Array prototype and so you don't see any extra functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM