Reputation: 1631
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?
Upvotes: 2
Views: 396
Reputation:
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++)
Upvotes: 0
Reputation: 437376
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.
Upvotes: 4
Reputation: 20155
Some properties are enumerables , some are not, so you wont see them in a for-in loop.
Upvotes: 1
Reputation: 54649
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).
Upvotes: 7