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

      

  • 相关阅读:
    基于goahead 的固件程序分析
    ELK
    weblogic doc
    shell 查找与替换
    简单的shell命令
    weblogic 安装配置打补丁
    WLST Hangs Up Because of Java VM ClassLoader Deadlock
    WLST
    常用weblogic搜索关键字
    How to Apply Patches to a WLS 8.1 Environment
  • 原文地址:https://www.cnblogs.com/hephec/p/4589991.html
Copyright © 2011-2022 走看看