Iterate over Javascript arrays with the keyword "in"

It seems that I do not understand the meaning of the in keyword in JavaScript.

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

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

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

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 is this happening? Is it caused by jQuery or does the behavior of the in keyword depend on whether the document is fully loaded or not?

+6
source share
2 answers

Some of the libraries loaded by jsFiddle extend the prototype of the array by default, so it shows these additional functions. jQuery does not extend the prototype of Array and therefore you do not see any additional features.

+2
source

This is due to prototype inheritance. The object not only shows its "own properties", but also all of its "properties of the ancestors."

To find only the 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 .

+3
source

Source: https://habr.com/ru/post/895398/


All Articles