不知道这个有没有特定的名称,但是我需要将一个由一维数组和简单元素组成的数组展开,以便报告所有直到叶子“节点”的组合。这里有一个例子,因为上面的描述让人想象力丰富:
// My input array contains single elements or 1D arrays:
let input = [1, 2, [3, 4], [5, 6]];
每次遇到一个数组时,展开过程会将路径分割成与数组元素数量相同的部分。
// current result = [1, 2]
// unconsumed input [[3, 4], [5, 6]]
// ->
// current result = [ [1, 2, 3], [1, 2, 4] ]
// current result = [ [1, 2, 3], [1, 2, 4] ]
// unconsumed input [[5, 6]]
// ->
// final result = [ [1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 3, 6], [1, 2, 4, 6] ]
我可能在复制和别名方面搞砸了,但似乎无法使其正常工作并处理特殊情况,例如:
let input1 = [1, 2, 3]; // No nested arrays
let input2 = []; // Empty input
尝试反向构建结果,因为在这里使用
.pop
很方便,但无法使其正常工作。
function flatPath(input, result = [[]]) {
while (input.length) {
const last = input.pop();
if (Array.isArray(last)) {
result = flatPath(last, [...result, ...result]);
} else {
for (let ar of result) {
result.push(last);
}
}
}
return result;
}
let result = flatPath([1, 2, [3, 4], [2, 5, 6] ]);
console.log(result);
但甚至连编译都无法通过(我正在使用TypeScript),因为我得到的只有:
参数 'input' 隐式具有 'any' 类型。
类型 'any' 的参数无法赋值给类型 'never' 的参数。
我的代码有什么问题,或者有没有更好(更符合惯用法)的方法来解决这个问题。