在 JavaScript 中使用递归展平嵌套数组 [英] Flatten nested arrays using recursion in JavaScript
本文介绍了在 JavaScript 中使用递归展平嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在保留顺序的同时展平嵌套数组,例如[[1, 2], 3, [4, [[5]]]]
应转换为[1, 2, 3, 4, 5]
.
I'm trying to flatten nested arrays while preserving the order, e.g. [[1, 2], 3, [4, [[5]]]]
should be converted to [1, 2, 3, 4, 5]
.
我正在尝试使用递归来这样做,但下面的代码不起作用,我不明白为什么.我知道还有其他方法可以做到这一点,但我想知道这有什么问题.
I'm trying to use recursion in order to do so, but the code below does not work and I don't understand why. I know there are other methods to do it, but I'd like to know what's wrong with this.
function flatten (arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatten(arr);
} else {
newArr.push(arr[i]);
}
}
return newArr;
}
flatten([[1, 2], 3, [4, [[5]]]]);
谢谢
推荐答案
递归调用flatten
时,需要将arr[i]
传递给它,然后concat结果与 newArr.所以替换这一行:
When calling flatten
recursively, you need to pass arr[i]
to it and then concat the result with newArr. So replace this line:
flatten(arr);
与:
newArr = newArr.concat(flatten(arr[i]));
这篇关于在 JavaScript 中使用递归展平嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文