在JavaScript中循环数组时,如何递归地调用内部本身的原型函数?

发布于 2025-01-22 00:30:19 字数 836 浏览 0 评论 0原文

我正在创建一个array.flat()方法的多填充,但是,在检查循环元素是一个数组之后,我在调用内部功能时面临问题,这需要进一步扁平。当编写不是原型的代码时,扁平化是正确的,但是当我尝试创建原型函数时,我无法获得扁平的数组。我很确定这个问题与“此”关键字有关。请看看我的代码。

这是代码

let arrayFlat = [1, 2, 3, [4, 5, 6, [7, 8, [9]], 10, [11, 12]], [13, [14, 15]]];

const flatArray = (array) => {
  let output = [];
  const flatten = (array) => {
    for (let i = 0; i < array.length; i++) {
      if (Array.isArray(array[i])) {
        flatten(array[i]);
      } else {
        output.push(array[i]);
      }
    }
    return output;
  };
  return flatten(array);
};

Array.prototype.myFlat = function () {
  let output = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      console.log(this[i]);
      this[i].myFlat();
    } else {
      output.push(this[i]);
    }
  }
  return output;
};

I'm creating a polyfill of Array.flat() method, however, I'm facing issues while calling the function within itself after checking that the looped element is an array and thats need to be flattened further. When a write a code that is not prototypal, the flattening is proper, however when I try to create a prototype function, I'm unable to get the flattened array. I'm pretty sure that the issue is related with the 'this' keyword. Please have a look at my code.

Here is the code

let arrayFlat = [1, 2, 3, [4, 5, 6, [7, 8, [9]], 10, [11, 12]], [13, [14, 15]]];

const flatArray = (array) => {
  let output = [];
  const flatten = (array) => {
    for (let i = 0; i < array.length; i++) {
      if (Array.isArray(array[i])) {
        flatten(array[i]);
      } else {
        output.push(array[i]);
      }
    }
    return output;
  };
  return flatten(array);
};

Array.prototype.myFlat = function () {
  let output = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      console.log(this[i]);
      this[i].myFlat();
    } else {
      output.push(this[i]);
    }
  }
  return output;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

锦爱 2025-01-29 00:30:19

在第一件代码中,您可以创建一个输出数组。当您递归调用FLATTEN时,代码始终推向完全相同的output array,该数组是flatten的关闭中。然后,一旦完成,您就会返回该数组。

在第二个代码中,您每次重复时都会创建一个新数组。每个递归将创建一个数组,使其自身变平,然后返回该新数组。但是返回值被忽略了,因此这些值不会到任何地方。

You have a few options

  1. Make the code basically identical to your first one, with an internal function for doing the recursion, and a closure variable used by all:
Array.prototype.myFlat = function () {
  let output = [];
  const flatten = (array) => {
    for (let i = 0; i < array.length; i++) {
      if (Array.isArray(array[i])) {
        flatten(array[i]);
      } else {
        output.push(array[i]);
      }
    }
    return output;
  };
  return flatten(this);
}
  1. Pass the output array as a parameter when you recurse:
//                                 VVVVVV--- added parameter
Array.prototype.myFlat = function (output = []) {
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      this[i].myFlat(output); // <---- forward the array along
    } else {
      output.push(this[i]);
    }
  }
  return output;
};
  1. Continue having separate arrays, but then随着堆栈的放松,将它们合并在一起:
Array.prototype.myFlat = function () {
  let output = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      output.push(...this[i].myFlat()); // <---- added output.push
    } else {
      output.push(this[i]);
    }
  }
  return output;
};

In your first piece of code, you create a single output array. When you recursively call flatten, the code is always pushing to the exact same output array, which is in the closure of flatten. Then once everything is done, you return that array.

In the second code, you create a new array every time you recurse. Each recursion will create an array, flatten itself, and then return that new array. But the return value is ignored, so these values don't go anywhere.

You have a few options

  1. Make the code basically identical to your first one, with an internal function for doing the recursion, and a closure variable used by all:
Array.prototype.myFlat = function () {
  let output = [];
  const flatten = (array) => {
    for (let i = 0; i < array.length; i++) {
      if (Array.isArray(array[i])) {
        flatten(array[i]);
      } else {
        output.push(array[i]);
      }
    }
    return output;
  };
  return flatten(this);
}
  1. Pass the output array as a parameter when you recurse:
//                                 VVVVVV--- added parameter
Array.prototype.myFlat = function (output = []) {
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      this[i].myFlat(output); // <---- forward the array along
    } else {
      output.push(this[i]);
    }
  }
  return output;
};
  1. Continue having separate arrays, but then merge them together as the stack unwinds:
Array.prototype.myFlat = function () {
  let output = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      output.push(...this[i].myFlat()); // <---- added output.push
    } else {
      output.push(this[i]);
    }
  }
  return output;
};
熟人话多 2025-01-29 00:30:19

我强烈支持保持类尽可能薄,将功能界面包装在可能的情况下 -

function myFlat(t) {
  return Array.isArray(t)
    ? t.reduce((r, v) => r.concat(myFlat(v)), [])
    : [t]
}

Array.prototype.myFlat = function() { return myFlat(this) }

console.log([1,[2,[3],4],[[5]],6,[[[7]]]].myFlat())
// [ 1, 2, 3, 4, 5, 6, 7 ]

I am a strong proponent of keeping classes as thin as possible, wrapping functional interfaces wherever possible -

function myFlat(t) {
  return Array.isArray(t)
    ? t.reduce((r, v) => r.concat(myFlat(v)), [])
    : [t]
}

Array.prototype.myFlat = function() { return myFlat(this) }

console.log([1,[2,[3],4],[[5]],6,[[[7]]]].myFlat())
// [ 1, 2, 3, 4, 5, 6, 7 ]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文