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

      

  • 相关阅读:
    bootstrap初识
    司徒正美居中方式
    css中的浮动(float)
    fio
    简易接口测试脚本
    字符加密
    Python 汉诺塔
    Python 找零问题
    Python 二分法
    Python 冒泡排序
  • 原文地址:https://www.cnblogs.com/hephec/p/4589991.html
Copyright © 2011-2022 走看看