How to list the properties of a JavaScript object?

后端 未结 17 2576
刺人心
刺人心 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:34

    As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            /* useful code here */
        }
    }
    

提交回复
热议问题