求JS输出二维数组所有组合的函数12
发布网友
发布时间:2023-10-27 14:00
我来回答
共2个回答
热心网友
时间:2024-12-01 11:25
给你个完美的递归算法,我敢说比他们的都好!
var array = [['A', 'B', 'C'], 'F', ['D', 'E'], 1, 'kyo', 'yugi111'];
var len = array.length;
var results = [];
var indexs = {};
function specialSort(start) {
start++;
if (start > len - 1) {
return;
}
if (!indexs[start]) {
indexs[start] = 0;
}
if (!(array[start] instanceof Array)) {
array[start] = [array[start]];
}
for (indexs[start] = 0; indexs[start] < array[start].length; indexs[start]++) {
specialSort(start);
if (start == len - 1) {
var temp = [];
for (var i = len - 1; i >= 0; i--) {
if (!(array[start - i] instanceof Array)) {
array[start - i] = [array[start - i]];
}
temp.push(array[start - i][indexs[start - i]]);
}
results.push(temp);
}
}
}
specialSort(-1);
console.log(results);
热心网友
时间:2024-12-01 11:26
arr = [["A","B","C"],"D",["E","F"],["J","G","H","I"]];
arr2 = [];
function all_arrs(arr,level,former){
if(arr.length == level + 1){
if(arr[level] instanceof Array){
for(var i = 0; i < arr[level].length; i++){
temp = former.slice(0);
temp.push(arr[level][i]);
arr2.push(temp);
}
}
else{
temp = former.slice(0);
temp.push(arr[level]);
arr2.push(temp);
}
}
else{
if(arr[level] instanceof Array){
for(var i = 0; i < arr[level].length; i++){
temp = former.slice(0);
temp.push(arr[level][i]);
all_arrs(arr,level+1,temp);
}
}
else{
temp = former.slice(0);
temp.push(arr[level]);
all_arrs(arr,level+1,temp);
}
}
}
all_arrs(arr,0,new Array(0));
其实我js不熟,所以有些地方可能比较繁琐。如果你有那几行重复代码的简单写法,一定要告诉我