Question

var result = function(){}
console.log("constructor" in result);//true
console.log("__proto__" in result);//true
console.log("prototype" in result);//true

for (var prop in result) {
   console.log(prop); // no output!!
}

when I use in for determining if property in the result, it returns true; But when I use for-in, there is no property in the result, why?

Was it helpful?

Solution

ref: https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in

A for...in loop does not iterate over non–enumerable properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype that are not enumerable, such as String's indexOf method or Object's toString method. The loop will iterate over all enumerable properties of the object or that it inherits from its constructor's proptotype (including any which overwrite built-in properties).

OTHER TIPS

That is because for...in only iterates over enumerable properties of its target. Enumerability is an attribute that properties may or may not have (along with writability and configurability); those that do not have it will not be exposed by for...in even though they of course still exist on the object.

MDN says this for for...in:

A for...in loop does not iterate over non–enumerable properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype that are not enumerable, such as String's indexOf method or Object's toString method. The loop will iterate over all enumerable properties of the object or that it inherits from its constructor's proptotype (including any which overwrite built-in properties).

On the other hand, in does not take enumerability into account and so returns true if a property exists without further deliberation.

Some properties are enumerables , some are not, so you wont see them in a for-in loop.

do

for (var prop in result) {
  console.log(result[prop]); // no output!!
 }

for..in does not itererate they way you expect. prop is index and the loop runs for each element in result.

it is the same as for(var i =0;i<result.length;i++)

for ... in just only enumeration object members

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top