【问题标题】:Find the length of an Array consisting of 2D arrays查找由二维数组组成的数组的长度
【发布时间】:2016-09-28 10:20:48
【问题描述】:

有没有办法找到这个数组的长度,以及它里面的所有子数组。意思是13而不是6?无需使用循环并将数组中的所有元素相加。

我正在寻找一个可以做到这一点的命令。

[1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]

【问题讨论】:

  • 仅使用第三方库(或手动)

标签: javascript arrays multidimensional-array


【解决方案1】:

试着把它弄平

[].concat.apply([], [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]).length

【讨论】:

    【解决方案2】:

    有点小技巧,但你可以做到

    arr.toString().split(',').length
    

    join(',') 也可以,它会使所有内容变平

    var arr = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];
    
    console.log(arr.toString().split(',').length)

    如果你想要的只是索引总数


    如果数组在索引中包含逗号,则可以将其删除以达到相同的效果

    JSON.stringify(arr).replace(/"(.*?)"/g,'1').split(',').length
    

    【讨论】:

    • @Maxx - 这就是为什么它是一个 hack,它适用于发布的示例,但不适用于其他所有示例。
    【解决方案3】:

    var input = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];
    var length = input.reduce(function(a, b) {
      return a + (Array.isArray(b) ? b.length : 1);
    }, 0);
    console.log(length);

    【讨论】:

    • 感谢这也有帮助!
    • @theNeighbourhoodGhost——但与其他答案相比,还达不到标准:(
    • not generic also ) 字符串也有 length 属性。 ['12', [3,4]] 将返回 4
    • @Maxx — object 也可以有长度属性 ({length:101})
    • @Rayon 好吧,在这种情况下,您的应用程序在生产中会出现错误或错误
    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 2023-03-16
    • 2019-11-17
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    相关资源
    最近更新 更多