在JavaScript中循环数组时,如何递归地调用内部本身的原型函数?
我正在创建一个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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一件代码中,您可以创建一个
输出
数组。当您递归调用FLATTEN
时,代码始终推向完全相同的output
array,该数组是flatten
的关闭中。然后,一旦完成,您就会返回该数组。在第二个代码中,您每次重复时都会创建一个新数组。每个递归将创建一个数组,使其自身变平,然后返回该新数组。但是返回值被忽略了,因此这些值不会到任何地方。
You have a few options
In your first piece of code, you create a single
output
array. When you recursively callflatten
, the code is always pushing to the exact sameoutput
array, which is in the closure offlatten
. 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
我强烈支持保持类尽可能薄,将功能界面包装在可能的情况下 -
I am a strong proponent of keeping classes as thin as possible, wrapping functional interfaces wherever possible -