How to use for in in js

for(variable in object)
   statement

variable is a var statement that declares a variable, an element of an array or a property of an object. Inside
the loop body, a property name of the object is assigned as a string to the variable variable.
Note: Some properties of objects are marked as read-only, permanent (undeletable) or non-enumerable in the same way, and these properties cannot be enumerated using for/in loops. While all user-defined properties are enumerable, many internal properties, including all internal methods, are not enumerable. In addition, objects can inherit properties from other objects, and those inherited user-defined properties can be enumerated using a for/in loop.

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

For example:
copy the code The code is as follows:


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

This is to enumerate all the items in a Element, of course, the above example can be used
Copy code The code is as follows:


for(var i=0,len=a.length;i<len;i++){ alert (
a[i]); out, but sometimes this method does not necessarily work. For example: copy code The code is as follows: var a = {"first":1,"









At this time, you can only use for in to exhaustively.
Whether an object can be exhaustively for in, we can judge by the propertyIsEnumerable property, as follows:

object.propertyIsEnumerable(propname) Whether the property propname can be seen through the for/in loop
A string containing the name of the object property
If object has A non-inherited property named propname, and the property is enumerable (that is, it can be enumerated with a for/in loop), then return true

Description:

Use a for/in statement to traverse the "enumerable" properties of an object , but not all properties of an object are enumerable, properties added to an object via JavaScript code are enumerable, while predefined properties (such as methods) of inner objects are usually not enumerable.

propertyIsEnumerable() The method does not detect the prototype chain, which means it only applies to the local properties of the object, and cannot detect the enumerability of inherited properties. The code is
copied as follows:


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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326838228&siteId=291194637