查找JavaScript数组值的所有组合
如何在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 r=allPossibleCases(allArrays); //outputs ["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]
临摹微笑