In JavaScript, Why doesn't for in return the contents of Object.prototype?
I get that using a for ... in loop will return all properties of an object, including those from its prototype chain, and using .keys() will give me an array of non-inher (basically for ... in combined with hasOwnProperty) but why doesn't a for ... in loop include things brought in from Object? ie why doesn't for .. in include the toString function from Object? Thanks!
A property of an object is defined by its key, value and also whether it is configurable, enumerable, writable. A non enumerable property will not show up in for in loops.
When an object property is created like this
var myObject = {};
myObject["a"] = 3;
It is by default configurable, enumerable and writable. It will show up in for in loops. It is possible to create non enumerable properties with Object.defineProperty
. You can check if a property is enumerable with .propertyIsEnumerable
:
myObject.propertyIsEnumerable("a"); // --> true
Object.propertyIsEnumerable("toString"); // --> false
链接地址: http://www.djcxy.com/p/27248.html
上一篇: 获取Json对象上的项目总数?