我目前有一个未知长度的 Javascript 数组,其中包含(未知长度的)字符串数组。我正在寻找一种方法来找到所有可能的组合,使用每个二级数组中的一个字符串。注意:字符串的顺序无关紧要。也就是说,对于:
[
[
'a',
'b'
],
[
'c',
'd'
]
]
我想返回:
[
'ac',
'ad',
'bc',
'bd'
]
或者,给定:
[
[
'a',
'b'
],
[
'1'
],
[
'i',
'j',
'k',
]
]
我想返回:
[
'a1i',
'a1j',
'a1k',
'b1i',
'b1j',
'b1k',
]
我觉得答案在于递归函数,但我似乎无法让它工作(变量作用域一直令人困惑,而且它只是持平)。
相反,我尝试了另一种创建结果数组的方法,循环遍历每个子数组并将每个字符串放入结果中,以便创建每个可能的组合:
function getArrayStrings(allTerms){
// get total number of possible combinations
var numberOfElements = 1;
$.each(allTerms, function(index, element){
numberOfElements *= element.length;
});
// create array of results
var result = [];
for(i = 0; i < numberOfElements; i ++){
result[i] = '';
}
// instantiate variables that will be used in loop
var elementToUse = 0;
var currentLength = 1;
var prevLength = 1;
// for each array, loop through values and add them to the relevant result element
$.each(allTerms, function(index, array){
// find length of current array
currentLength = array.length;
elementToUse = 0;
// for each of the elements in the results array
for(i = 0; i < numberOfElements; i ++){
// change the element to use if you've looped through the previous length (but not if it's first result
if(i !== 0 && i % prevLength === 0){
elementToUse ++;
}
// return to using the first element if you've reached the last element in the sub array
if(elementToUse % currentLength === 0){
elementToUse = 0;
}
result[i] += '.' + array[elementToUse];
}
prevLength = array.length * prevLength;
});
console.log(result.join(''));
return result.join('');
}
这确实有效,但我想知道是否有人知道更简单的功能;我觉得这里面已经有一些 Javascript(或 jQuery)函数,但我找不到它。
有没有人遇到过这样的挑战?如果是这样,您是如何处理的?
最佳答案
简单递归:
var a = [ [ 'a', 'b' ],
[ '1' ],
[ 'i', 'j', 'k' ]
];
function combo( arr, i, j ) {
if (i===j-1) return arr[i];
var res = [];
arr[i].forEach( function(a) {
combo( arr, i+1, j ).forEach( function(b) {
res.push(a+b);
});
});
return res;
}
console.log( combo(a, 0, a.length) );
关于javascript - 在 Javascript 中组合两个或多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31712707/