// 测试数据定义
let symbolKey = Symbol('symbolKey');
function Obj(){
this.ownKey = 1;
this[symbolKey] = 2;
}
Obj.prototype.prototypeKey = 3;
let o = new Obj();
Object.defineProperty(o, 'unenumerableKey', {
enumerable: false,
value: 4
})
for...in
Get all enumerable properties (local properties or custom properties on the prototype chain)for(let key in o){ console.log(key) }// ownKey
Object.getOwnPropertyNames(o)
Get all local attributes, including non-enumerable local attributesObject.getOwnPropertyNames(o); // ["ownKey", "unenumerableKey"]
Object.keys(o)
Get all local enumerable propertiesObject.keys(o); // ownKey
Note:
- The property that can be traversed must be a local enumerable property
- Local enumerable attributes may not necessarily be traversable
Symbol
as the local attribute of the key, yesenumerable
, but the key cannot be obtained by the above three methods.