zoukankan      html  css  js  c++  java
  • js 获取对象属性个数

    js 获取对象属性个数

    方法一:

        var attributeCount = function(obj) {
            var count = 0;
            for(var i in obj) {
                if(obj.hasOwnProperty(i)) {  // 建议加上判断,如果没有扩展对象属性可以不加
                    count++;
                }
            }
            return count;
        }
    
        var testObj = {
            name1: "value1",
            name2: "value2"
        };
    
        alert(attributeCount(testObj)); // 2

    方法二:

      function TestObj(name, age) {
          this.name = name,
            this.age = age
      }
    
      TestObj.prototype.proCount = function() {
          var count = 0
          for(pro in this) {
              if(this.hasOwnProperty(pro)) { // 这里扩展了对象,所以必须判断
                  count++;
              }
          }
          return count;
      }
      var testObj = new TestObj('名称', 12);
      alert(testObj.proCount()); // 2

    方法三:

        var testObj = {
          name1: "value1",
          name2: "value2"
        };
    
        alert(Object.getOwnPropertyNames(testObj).length); // 2
  • 相关阅读:
    玩游戏(dfs)
    Find them, Catch them(并查集)
    Shredding Company(dfs)
    Sudoku(dfs)
    Network Saboteur(dfs)
    棋盘问题(dfs)
    Curling 2.0(dfs)
    A Knight's Journey(dfs)
    15. 3Sum
    12. Integer to Roman
  • 原文地址:https://www.cnblogs.com/ooo0/p/6534333.html
Copyright © 2011-2022 走看看