如何生成 N 个可变长度的 JavaScript 数组中值的所有组合?
假设我有 N 个 JavaScript 数组,例如
var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third = ['f', 'g', 'h', 'i', 'j'];
(本例中为三个数组,但问题的数组数为 N。)
我想输出它们值的所有组合,以产生
aef
aeg
aeh
aei
aej
bef
beg
....
dej
编辑:这是我工作的版本,使用 ffriend 接受的答案作为基础。
var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length ===1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var c in allCasesOfRest) {
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + allCasesOfRest[c]);
}
}
return result;
}
}
var results = allPossibleCases(allArrays);
//outputs ["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]