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

问题描述 投票:0回答:1

所以,我有一个像这样的数组 常量数组=[1,2,3,4,[5,6],[[[[7,8]]]]]。我知道我可以通过像这样的扁平函数来使其扁平化。 array.flat(4) // [1,2,3,4,5,6,7,8]

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

javascript arrays
1个回答
0
投票

您可以使用

展平未知长度的数组
array.flat(Infinity)

您可以使用带有堆栈的循环自己对元素进行计数,这会更有效,因为您不创建新数组:

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)  [arr,i] = path.pop();

    }

    return count;

}

还有一个基准:

` Chrome/124
---------------------------------------------------------------------------------
>              n=6       |       n=60        |      n=600       |     n=6000     
count    ■ 1.00x x1m 153 | ■ 1.00x x100k 153 | ■ 1.00x x10k 114 | ■ 1.00x x1k 137
flat()     1.36x x1m 208 |   1.27x x100k 194 |   1.90x x10k 217 |   1.67x x1k 229
---------------------------------------------------------------------------------
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)  [arr,i] = 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));

© www.soinside.com 2019 - 2024. All rights reserved.