zoukankan      html  css  js  c++  java
  • How to list the properties of a JavaScript object

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

      

    What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:

    keys == ["ircEvent", "method", "regex"]
    

      

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

    var keys = Object.keys(myJSONObject);
    

      

    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.

    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 */
        }
    }
    

      

  • 相关阅读:
    线程池。
    等待唤醒机制。
    第一册:lesson 131.
    线程同步机制。
    第一册: lesson 129。
    线程实现方式。
    第一册:lesson 125.
    第一册:Lesson 123.
    黄渤的谈话。
    K3 KFO 手册
  • 原文地址:https://www.cnblogs.com/hephec/p/4589991.html
Copyright © 2011-2022 走看看