函数可以拼合多个嵌套数组的数组,而无需在JavaScript中进行递归

假设我们有一个嵌套的数字数组,如下所示:

const arr = [1, 4, 5, [
   5, 6, [
      6, 19, 5, [5]
   ], [5, 7, 6, [6, 8]], 8
], 6];

我们需要编写一个JavaScript函数,该函数需要一个嵌套数组,理想情况下嵌套到任意级别。

然后,我们的函数应该准备并返回一个新数组,该数组不只是输入数组的扁平版本。

在编写函数时,有两个条件需要避免-

  • 我们不能在代码的任何地方使用任何自定义递归函数。

  • 我们无法在代码中使用Array.prototype.flat()方法。

示例

为此的代码将是-

const arr = [1, 4, 5, [
   5, 6, [
      6, 19, 5, [5]
   ], [5, 7, 6, [6, 8]], 8
], 6];
const flattenWithoutRecursion = (arr = []) => {
   const res = [];
   let level = 0, ref = [arr], counter = [0];
   while(level >= 0){
      if (counter[level] >= ref[level].length) {
         level--;
         continue;
      };
      if (Array.isArray(ref[level][counter[level]])) {
         ref[level + 1] = ref[level][counter[level]]
         counter[level]++;
         level++;
         counter[level] = 0;
         continue;
      };
      res.push(ref[level][counter[level]]);
      counter[level]++;
   };
   return res;
};
console.log(flattenWithoutRecursion(arr));

输出结果

控制台中的输出将是-

[
   1, 4, 5, 5, 6, 6,
   19, 5, 5, 5, 7, 6,
   6, 8, 8, 6
]
猜你喜欢