js⼆维数组所有排列组合(马井堂)
js ⼆维数组 所有排列组合,⽅法如下:
var arr =[
['a','b'],
['1','2','3'],
['x','y'],
]
var  results =[];
var result =[];
doExchange(arr,0);
function doExchange(arr, index){
for(var i =0; i<arr[index].length; i++){
result[index]= arr[index][i];
if(index != arr.length -1){
doExchange(arr, index +1)
}else{
results.push(result.join(','))
}
}
}
console.log( results);
结果:
/
/ [‘a,1,x’, ‘a,1,y’, ‘a,2,x’, ‘a,2,y’, ‘a,3,x’, ‘a,3,y’, ‘b,1,x’, ‘b,1,y’, ‘b,2,x’, ‘b,2,y’, ‘b,3,x’,‘b,3,y’]
看看另外⼀种形式的⼆维数组⾃由排列组合,可能更加适合项⽬实例:
var arr =[[{name:11,code:1},{name:12,code:1}],[{name:21,code:1},{name:22,code:1}]];
var results =[];
var result =[];
doExchange(arr,0);
function doExchange(arr, index){
for(var i =0; i<arr[index].length; i++){
result[index]= arr[index][i].name;
if(index != arr.length -1){
doExchange(arr, index +1)
}else{
results.push(result.join(','))
}
}
}
console.log( results);//
结果:
[‘11,21’, ‘11,22’, ‘12,21’, ‘12,22’]
js 二维数组

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。