Explanation of the use of for in statement in js

  • 2020-06-01 08:13:53
  • OfStack


 for(variable in object)
   statement

variable is an var statement that declares a variable, an element of an array, or an attribute of an object
Inside the body of the loop, one property name of the object is assigned to the variable variable as a string.

Note: some of the properties of the object are marked in the same way as read-only, permanent (not deleted), or unenumerable, and these properties cannot be enumerated using the for/in loop. While all user-defined properties can be enumerated, many internal properties, including all internal methods, are not enumerable. In addition, objects can inherit the properties of other objects, and those user-defined properties that have been inherited can be enumerated using the for/in loop.

for(var i=0;i < len; i++) 1 can generally be replaced by for in.

Such as:


var a = ["a","b","c"];
for(var el in a){
alert(a[el]);
}

This is just a poor list of all the elements in a, although this example can be used

for(var i=0,len=a.length;i<len;i++){
alert(a[i]);
}

This is a way of looping through the list, but sometimes it doesn't work.
Such as:

var a = {"first":1,"second":2,"third":3};

At this point you have to use for in to do the dirty work.

Whether an object can perform for in exhaustive analysis, we can judge by propertyIsEnumerable attribute, as follows:

Whether object.propertyIsEnumerable (propname) can see the properties through the for/in loop
propname 1 string containing the name of the object property
If object has a non-inherited property named propname and that property is enumerable (that is, the for/in loop can enumerate it), true is returned

Description:

The "enumerable" properties of an object can be traversed by for/in statements, but not all the properties of an object are enumerable. The properties added to the object by JavaScript code are enumerable, while the predefined properties (such as methods) of internal objects are usually not enumerable.

The propertyIsEnumerable() method does not detect the prototype chain, which means that it applies only to local properties of an object and cannot detect the enumeration of inherited properties


var o=new Object();
o.x=3.14;
o.propertyIsEnumerable("x");//true
o.propertyIsEnumerable("y");//false have not the property
o.propertyIsEnumerable("toString");//false inherited
Object.prototype.propertyIsEnumerable("toString");//false nonenumerable


Related articles: