代码之家  ›  专栏  ›  技术社区  ›  Vilayat Safarov

如何检查数组中包含多少[]个符号

  •  0
  • Vilayat Safarov  · 技术社区  · 3 周前

    所以,我有一个这样的数组 const数组=[1,2,3,4,[5,6],[[[7,8]]]]。我知道我可以通过这样的函数使它变平。 array.平面(4)//[1,2,3,4,5,6,7,8]

    但正如你们所知,当我们知道这个符号的数组外部计数时,我们可以这样做。但是我们可以获取 我们不知道数组中有多少个符号的任何数据。我的问题是如何检查 数组中有多少个[]-这个符号。

    2 回复  |  直到 3 周前
        1
  •  0
  •   Alexander Nenashev Jhony Spark    3 周前

    您可以使用压平未知深度的数组

    array.flat(Infinity).length
    

    您可以自己计算元素,但使用循环和堆栈而无需递归(没有最大调用堆栈大小错误),这将更有效,因为您不创建新数组:

    console.log(countNestedArrayItems([1,2,3,4,[5,6],[[[[7,8]]]]]));
    
    function countNestedArrayItems(arr) {
    
        let count = 0;
        const path = [];
    
        for (let i = 0; i < arr.length; i++) {
    
            const item = arr[i];
    
            if (Array.isArray(item)) {
                path.push(arr, i);
                i = -1;
                arr = item;
                continue;
            }
    
            count++;
            while(i === arr.length - 1 && path.length)  i = path.pop(), arr = path.pop();
    
        }
    
        return count;
    
    }

    以及一个基准:

    ` Chrome/124
    -----------------------------------------------------------------------------------
    >              n=6       |       n=60        |       n=600       |      n=6000     
    count    ■ 1.00x x1m 116 | ■ 1.00x x100k  94 | ■ 1.00x x100k 927 | ■ 1.00x x10k 860
    flat()     1.75x x1m 203 |   2.17x x100k 204 |   2.29x  x10k 212 |   2.60x  x1k 224
    -----------------------------------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    

    const $chunk = [1,2,3,4,[5,6],[[[[7,8,[1,2,3,4,[5,6],[[[[7,8]]]]]]]]]];
    const $input = [];
    
    function countNestedArrayItems(arr) {
    
        let count = 0;
        const path = [];
    
        for (let i = 0; i < arr.length; i++) {
    
            const item = arr[i];
    
            if (Array.isArray(item)) {
                path.push(arr, i);
                i = -1;
                arr = item;
                continue;
            }
    
            count++;
            while(i === arr.length - 1 && path.length)  i = path.pop(), arr = path.pop();
    
        }
    
        return count;
    
    }
    // @benchmark count
    countNestedArrayItems($input);
    
    // @benchmark flat()
    $input.flat(Infinity).length;
    
    /*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));
        2
  •  0
  •   maxis112    3 周前

    你的问题不是很清楚,这有帮助吗?

    const array = [1, 2, 3, 4, [5, 6], [[[[7, 8]]]]];
    
    function countNestedArrays(arr) {
      let count = 0;
      for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
          count++;
          count += countNestedArrays(arr[i]);
        }
      }
      return count;
    }
    
    console.log(countNestedArrays(array));