JS二维数组排序组合

  需求是这样的:http://q.cnblogs.com/q/29093/

  这里简述一下:    

现在有一个不确定长度的数组.
比如:
var temp=[
["Fu","Hai","Huan"],
["Wei","You"],
["Chong","Tong","Zhong"]
];
每一个数组的长计都不确定 ,
如何 遍历这个数组
得到如: FuWeiChong ,FuWeiTong
这样的数据

  这是一个JS二维数组排序组合问题,用递规法解决如下:

function doExchange(doubleArrays){
var len=doubleArrays.length;
if(len>=2){
var len1=doubleArrays[0].length;
var len2=doubleArrays[1].length;
var newlen=len1*len2;
var temp=new Array(newlen);
var index=0;
for(var i=0;i<len1;i++){
for(var j=0;j<len2;j++){
temp[index]=doubleArrays[0][i]+
doubleArrays[1][j];
index++;
}
}
var newArray=new Array(len-1);
for(var i=2;i<len;i++){
newArray[i-1]= doubleArrays[i];
}
newArray[0]=temp;
return doExchange(newArray);
}
else{
return doubleArrays[0];
}
}

  测试代码:

1 var temparr=[
2 ["Fu","Hai","Huan"],
3 ["Wei","You"],
4 ["Chong","Tong","Zhong"]];
5 var ret = doExchange(temparr);
6 console.log("共有:" + ret.length + "种组合!");
7 for (var i = 0; i < ret.length; i++) {
8 console.log(ret[i]);
9 }

效果如下:

posted @ 2011-10-20 13:12  artwl  阅读(7297)  评论(0编辑  收藏  举报

个人简介

var ME = {
	"name": "土豆/Artwl",
	"job": "coding",
	"languages": [
		"JS", "HTML",
                "CSS", "jQuery"
		"MVC",".NET",
		"设计模式"
	],
	"hobby": [
		"阅读", "旅游",
		"音乐", "电影"
	]
}
TOP