How to list the properties of a JavaScript object?

后端 未结 17 2588
刺人心
刺人心 2020-11-22 00:34

Say I create an object thus:

var myObject =
        {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};

What is

17条回答
  •  忘了有多久
    2020-11-22 01:12

    Object.getOwnPropertyNames(obj)

    This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

    In JS, every property has a few properties, including a boolean enumerable.

    In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

    Example:

    var o = Object.create({base:0})
    Object.defineProperty(o, 'yes', {enumerable: true})
    Object.defineProperty(o, 'not', {enumerable: false})
    
    console.log(Object.getOwnPropertyNames(o))
    // [ 'yes', 'not' ]
    
    console.log(Object.keys(o))
    // [ 'yes' ]
    
    for (var x in o)
        console.log(x)
    // yes, base
    

    Also note how:

    • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
    • for in does

    More about the prototype chain here: https://stackoverflow.com/a/23877420/895245

提交回复
热议问题