查找JavaScript數(shù)組值的所有組合如何在N個(gè)可變長度的JavaScript數(shù)組中生成所有值的組合?假設(shè)我有N個(gè)JavaScript數(shù)組,例如var first = ['a', 'b', 'c', 'd'];var second = ['e'];var third = ['f', 'g', 'h', 'i', 'j'];(在這個(gè)例子中有三個(gè)數(shù)組,但它有N個(gè)數(shù)組用于解決問題。)我想輸出它們的所有值的組合,以產(chǎn)生aef
aeg
aeh
aei
aej
bef
beg....dej編輯:這是我工作的版本,使用ffriend接受的答案作為基礎(chǔ)。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 r=allPossibleCases(allArrays);
//outputs ["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]
查找JavaScript數(shù)組值的所有組合
泛舟湖上清波郎朗
2019-07-30 11:22:53