【问题标题】:iterating an object properties迭代对象属性
【发布时间】:2023-03-24 12:06:01
【问题描述】:

有没有办法迭代一个对象的属性和方法。我需要像这样编写一个实用函数:

function iterate(obj)
{
    //print all obj properties     
    //print all obj methods
}

所以运行这个函数:

iterate(String);

将打印:

property: lenght
function: charAt
function: concat...

有什么想法吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    应该这么简单:

    function iterate(obj) {
        for (p in obj) {
            console.log(typeof(obj[p]), p);
        }
    }
    

    注意:console.log 函数假设您使用的是firebug。此时,如下:

    obj = {
        p1: 1, 
        p2: "two",
        m1: function() {}
    };
    
    iterate(obj);
    

    会返回:

    number p1
    string p2
    function m1
    

    【讨论】:

    • 看来运行你的例子是可行的。但是,当我使用 String 类时,它没有返回任何内容。迭代(字符串);我也试过: var s = "sss";迭代;
    • 当你迭代一个字符串时,它会逐步遍历每个字符。尝试传递 String(s),以将字符串包装在对象中。
    【解决方案2】:

    this other question 中查看我的答案,但您无法读取这样的内置属性。

    【讨论】:

      【解决方案3】:

      这仅适用于现代浏览器(Chrome、Firefox 4+、IE9+),但在 ECMAScript 5 中,您可以使用 Object.getOwnPropertyNames 获取对象的所有属性。从原型中获取继承的属性只需要一点额外的代码。

      // Put all the properties of an object (including inherited properties) into
      // an object so they can be iterated over
      function getProperties(obj, properties) {
          properties = properties || {};
      
          // Get the prototype's properties
          var prototype = Object.getPrototypeOf(obj);
          if (prototype !== null) {
              getProperties(prototype, properties);
          }
      
          // Get obj's own properties
          var names = Object.getOwnPropertyNames(obj);
          for (var i = 0; i < names.length; i++) {
              var name = names[i];
              properties[name] = obj[name];
          }
      
          return properties;
      }
      
      function iterate(obj) {
          obj = Object(obj);
      
          var properties = getProperties(obj);
      
          for (var name in properties) {
              if (typeof properties[name] !== "function") {
                  console.log("property: " + name);
              }
          }
          for (var name in properties) {
              if (typeof properties[name] === "function") {
                  console.log("function: " + name);
              }
          }
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用 for 循环来迭代对象的属性。

        这是一个简单的例子

        var o ={'test':'test', 'blah':'blah'};
        
        for(var p in o)
            alert(p);
        

        【讨论】:

        • 如果属性是对象的键怎么办?
        猜你喜欢
        • 1970-01-01
        • 2010-10-03
        • 2016-02-26
        • 1970-01-01
        • 2011-09-18
        • 2011-06-18
        • 2013-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多