Object traversal method

Keywords: Javascript Attribute

Different return values of different methods traversing objects

Pre Code:

    function Obj() {
        // Add properties directly on this
        this.prop_this = 'prop_this';
        // Add symbol attribute on this
        this[Symbol.for('prop_symbol')] = 'prop_symbol';
    }
    
    // Add attribute on Prototype
    Obj.prototype.propProto = 'prop_proto';
    
    const obj = new Obj();
    
    // Set traversal property enumerable to no
    Object.defineProperty(obj, 'prop_dontEnum', {
        value: 'prop_dontEnum',
        enumerable: false,
        writable: false,
        configurable: false
    });
  1. getOwnPropertyDescriptors can get all their own property descriptions

    console.log(Object.getOwnPropertyDescriptors(obj));
    // { 
          prop_this: 
           { value: 'prop_this',
             writable: true,
             enumerable: true,
             configurable: true },
          prop_dontEnum: 
           { value: 'prop_dontEnum',
             writable: false,
             enumerable: false,
             configurable: false },
          [Symbol(prop_symbol)]: 
           { value: 'prop_symbol',
             writable: true,
             enumerable: true,
             configurable: true } 
         }
  2. getOwnPropertyNames can get its own properties except for symbols, and getOwnPropertySymbols can be used to get its own symbol value

    console.log(Object.getOwnPropertyNames(obj));
    // [ 'prop_this', 'prop_dontEnum' ]
    
    console.log(Object.getOwnPropertySymbols(obj));
    // [ Symbol(prop_symbol) ]
  3. for...in can get its own enumeration of properties and prototype properties except symbol

    for(var i in obj) {
        console.log(i);
    }
    // prop_this  propProto
  4. Object.keys and Object.values can only obtain their own enumerable attributes except for symbol s

    console.log(Object.keys(obj));
    // [ 'prop_this' ]
  5. Reflect.ownKeys(obj) can get all its properties

    console.log(Reflect.ownKeys(obj));
    // [ 'prop_this', 'prop_dontEnum', Symbol(prop_symbol) ]

Posted by kenle on Fri, 01 May 2020 04:13:47 -0700