也许这是个愚蠢的问题,但我无法意识到是否可以在不递归的情况下展平多维数组?
我有一个用递归写的解决方案:
function transform (arr) {
var result = [];
arr.forEach(flatten)
function flatten (el) {
if (Array.isArray(el)) {
return el.forEach(flatten);
}
return result.push(el);
}
return result;
}
要展平的数组示例:
[1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10]
和执行:
var a = [1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10];
var r = transform(r);
console.log(r); // [1, {a: [2, 3]}, 4, 5, 6, 7, 8, 9, 10]
谢谢!
最佳答案
您可以使用堆栈。当您发现嵌套数组时,只需将其替换为它的项即可。
function flatten(arr) {
var result = [];
var stack = arr, first;
while (stack.length > 0) {
first = stack[0];
if (Array.isArray(first)) {
// Replace the nested array with its items
Array.prototype.splice.apply(stack, [0, 1].concat(first));
} else {
result.push(first);
// Delete the first item
stack.splice(0, 1);
}
}
return result;
}
关于javascript - 在没有递归的情况下展平多个嵌套数组的数组 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303369/