【问题标题】:Count elements in a multidimensional array计算多维数组中的元素
【发布时间】:2025-12-07 21:50:01
【问题描述】:

我得到了这个代码:

loadData : function(jsonArray) {
var id = $(this).attr("id");

for(var i in jsonArray) {
    $("#"+id+" tbody").append('<tr class="entry-details page-1 entry-visible" id="entry-'+i+'"></tr>');

    var header = {
        1: "time",
        2: "project",
        3: "task"
    }
    var col = 1;
    while(col <= jsonArray[i].length) {
        $("#"+id+" tbody #entry-"+i).append("<td>"+jsonArray[i][header[col]]+"</td>")
        col++
}}

它将采用类似于以下内容的 JSON 数组

{"1":{"project":"RobinsonMurphy","task":"Changing blog templates","time":"18\/07\/11 04:32PM"},"2":{"project":"Charli...

代码应该遍历行(它会这样做),然后遍历数据列。

我面临的问题是为了将列数据放在正确的列中,我需要计算一行返回多少条数据。我试过 jsonArray[i].length,但是这返回 undefined。

任何帮助将不胜感激

【问题讨论】:

    标签: javascript multidimensional-array counting


    【解决方案1】:

    你根本没有任何数组,只有对象。

    要计算对象中的项目,请创建一个简单的函数:

    function countInObject(obj) {
        var count = 0;
        // iterate over properties, increment if a non-prototype property
        for(var key in obj) if(obj.hasOwnProperty(key)) count++;
        return count;
    }
    

    现在,您可以拨打countInObject(jsonArray[i])

    【讨论】:

    • @Brad Morris:请接受对您有帮助的答案,谢谢:)
    • 对不起,我的错,* 的新手!固定:)
    【解决方案2】:

    像这样:

    Object.size = function(obj) {
        var size = 0, key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) size++;
        }
        return size;
    };
    
    // Get the size of an object
    var size = Object.size(myArray);
    

    Length of a JavaScript object

    【讨论】:

      【解决方案3】:

      看看那个小提琴: http://jsfiddle.net/Christophe/QFHC8/

      关键是

      for (var j in jsonArray[i]) {
      

      而不是

      while (col <= jsonArray[i].length) {
      

      【讨论】:

        【解决方案4】:

        jsonArray[i].length 不起作用,因为 jsonArray[i] 是字典而不是数组。您应该尝试以下方法:

        for(var key in jsonArray[i]) {
             jsonArray[i][key]
        }
        

        【讨论】:

          【解决方案5】:

          我一直面临同样的问题,我编写了一个函数,该函数将多维数组/对象中的所有标量值组合在一起。如果对象或数组是空的,那么我假设它不是一个值,所以我不会对它们求和。

          function countElements(obj) {
            function sumSubelements(subObj, counter = 0) {
              if (typeof subObj !== 'object') return 1; // in case we just sent a value
              const ernation = Object.values(subObj);
              for (const ipated of ernation) {
                if (typeof ipated !== 'object') {
                  counter++;
                  continue;
                }
                counter += sumSubelements(ipated);
              }
              return counter;
            }
            return sumSubelements(obj);
          }
          
          let meBe = { a: [1, 2, 3, [[[{}]]]], b: [4, 5, { c: 6, d: 7, e: [8, 9] }, 10, 11], f: [12, 13], g: [] };
          const itution = countElements(meBe);
          console.log(itution); // 13
          
          let tuce = [1,2];
          console.log(countElements(tuce)); // 2
          
          console.log(countElements(42)); // 1
          

          或者,如果您想在生产中使用它,您甚至可以考虑将其添加到 Object 原型中,如下所示:

          Object.defineProperty(Object.prototype, 'countElements', {
            value: function () {
              function sumSubelements(subObj, counter = 0) {
                const subArray = Object.values(subObj);
                for (const val of subArray) {
                  if (typeof val !== 'object') {
                    counter++;
                    continue;
                  }
                  counter += sumSubelements(val);
                }
                return counter;
              }
              return sumSubelements(this);
            },
            writable: true,
          });
          
          console.log(meBe.countElements()); // 13
          console.log([meBe].countElements()); // 13; it also works with Arrays, as they are objects
          

          【讨论】: