JavaScript property traversal

// 测试数据定义
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
})
  1. for...in Get all enumerable properties (local properties or custom properties on the prototype chain)
    for(let key in o){
          
          
    	console.log(key)
    }// ownKey
    
  2. Object.getOwnPropertyNames(o) Get all local attributes, including non-enumerable local attributes
    Object.getOwnPropertyNames(o);	// ["ownKey", "unenumerableKey"]
    
  3. Object.keys(o) Get all local enumerable properties
    Object.keys(o);	// ownKey
    

Note:

  1. The property that can be traversed must be a local enumerable property
  2. Local enumerable attributes may not necessarily be traversable
    Symbol as the local attribute of the key, yes enumerable, but the key cannot be obtained by the above three methods.

Guess you like

Origin blog.csdn.net/SJ1551/article/details/109287121