在 JavaScript 中从包含 m 个元素的 n 个数组生成组合
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,从包含 m 个元素的 n 个数组生成组合。
例如 −
考虑此数据 −
const arr = [ [0,1], [0,1,2,3], [0,1,2] ]
3 个子数组,每个子数组包含不同数量的元素。
我们想要做的是通过组合每个数组中的一个项目来获得所有组合。
例如 −
0,0,0 // 数组 0 中的项目 0,数组 1 中的项目 0,数组 2 中的项目 0 0,0,1 0,0,2 0,1,0 0,1,1 0,1,2 0,2,0 0,2,1 0,2,2
等等。
如果数组数量是固定的,那么进行硬编码实现就很容易了。但数组数量可能会有所不同 −
const arr1 = [[0,1], [0,1]]; const arr2 = [[0,1,3,4], [0,1], [0], [0,1]];
示例
其代码为 −
const arr = [
[0,1],
[0,1,2,3],
[0,1,2]
]
const combineAll = (array) => {
const res = [];
let max = array.length−1;
const helper = (arr, i) => {
for (let j=0, l=array[i].length; j<l; j++) {
let copy = arr.slice(0);
copy.push(array[i][j]);
if (i==max)
res.push(copy);
else
helper(copy, i+1);
};
};
helper([], 0);
return res;
};
console.log(combineAll(arr));
控制台中的输出将是 −
[ [ 0, 0, 0 ], [ 0, 0, 1 ], [ 0, 0, 2 ], [ 0, 1, 0 ], [ 0, 1, 1 ], [ 0, 1, 2 ], [ 0, 2, 0 ], [ 0, 2, 1 ], [ 0, 2, 2 ], [ 0, 3, 0 ], [ 0, 3, 1 ], [ 0, 3, 2 ], [ 1, 0, 0 ], [ 1, 0, 1 ], [ 1, 0, 2 ], [ 1, 1, 0 ], [ 1, 1, 1 ], [ 1, 1, 2 ], [ 1, 2, 0 ], [ 1, 2, 1 ], [ 1, 2, 2 ], [ 1, 3, 0 ], [ 1, 3, 1 ], [ 1, 3, 2 ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

