How to list the properties of a JavaScript object?

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

Say I create an object thus:

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

What is

17条回答
  •  Happy的楠姐
    2020-11-22 01:20

    In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

    var keys = Object.keys(myObject);
    

    The above has a full polyfill but a simplified version is:

    var getKeys = function(obj){
       var keys = [];
       for(var key in obj){
          keys.push(key);
       }
       return keys;
    }
    

    Alternatively replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.

提交回复
热议问题