如图,属性组合如何显示 比如下面的这种结构的话,可以直接写死 3 层嵌套
a = [1,2]
b = [3,4]
c = [5]
for(var i in a){
for(var j in b){
for(var k in c){
console.log(a[i],b[j],c[k])
}
}
}
---
1 3 5
1 4 5
2 3 5
2 4 5
但是属性的个数都是不定的, 假设数据结构为 a = [[1,2],[3,4],[5]...]又怎么实现呢
1
Exin 2018-08-07 17:29:38 +08:00
伪代码:
func combs(arr, ...rest): r = [] for(var i in arr) { r.push(...combs(...rest).map(comb => [i, ...comb])) } return r } |
2
yidinghe 2018-08-07 17:34:49 +08:00
var arr = [[1,2,3,4],[5,6,7]];
for (var i1=0; i1<arr.length;i1++) { for(var i2=0;i2<arr[i1].length;i2++) { console.log(arr[i1][i2]); } } |
3
vincenth520 OP 已经解决了.
``` 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); ``` |