["A","B","C"]与["1","2","3"]组合的结果:
<html><head>
<title>js两个数组排列组合</title>
<script type="text/javascript">
var a = ["A","B","C"]
var b = ["1", "2","3"]
window.onload = function () {
var a1 = new objPL(a)//计算数组a的排列组合
var b1 = new objPL(b)//计算数组b的排列组合
var str = ""
var n = 0
//a1和b1的排列组合个数就是两者相乘(双层循环)
for (var i = 0 i < a1.length i++) {
for (var j = 0 j < b1.length j++) {
str += a1[i] + b1[j] + " "
n++
}
str += "<br/>"
}
document.write("共" + n + "个<br/>")
document.write(str)
}
//取数组的排列组合
function objPL(arr) {
this.a = arr
this.r = []
this.n = 0
//从M个数里面取N个(递归)
this.mGetN = function (curIndex, num, curSelect) {
if (num == 0) {
this.r[this.n++] = curSelect return
}
if (this.a.length - curIndex < num) return
this.mGetN(curIndex + 1, num - 1, curSelect + this.a[curIndex])
this.mGetN(curIndex + 1, num, curSelect)
}
for (var i = 1 i <= this.a.length i++) {
this.mGetN(0, i, "")
}
return this.r
}
</script>
</head>
<body></body>
</html>
["A","B","C"]与["1","2","3"]组合的结果:
楼上的答案确认是对的,再给你一个答案,我觉得我写的比楼上的啰嗦。
/*var datas = [
['红色', '蓝色'],
['XL'],
['图片', '文字']
]
*/
/*
var datas = [
['红色', '蓝色'],
['XL'],
['图片', '文字'],
[1,2,3,4,5,6,7,8]
]
var datas = [
['红色', '蓝色'],
['XL','MS'],
['图片', '文字']
]
*/
var datas = [
['红色', '蓝色'],
['XL','MS'],
['图片', '文字'],
['WIN','LINUX','UNIX','OSX']
]
var merge1 = function(arr1,arr2) {
var result = []
for(var i=0i<arr1.lengthi++) {
for(j=0j<arr2.lengthj++) {
var tmp = []
tmp.push(arr1[i])
tmp.push(arr2[j])
result.push(tmp)
}
}
return result
}
var merge2 = function(arr1,arr2) {
var result = []
for(var i=0i<arr2.lengthi++) {
for(var j=0j<arr1.lengthj++) {
var tmp = copy(arr1[j])
tmp.push(arr2[i])
result.push(tmp)
}
}
return result
}
var copy = function(arr) {
var newArr = []
return newArr.concat(arr)
}
var iterator = function(data) {
return {
data:data,
len:data.length,
current:0,
hasNext:function(){
return this.current < this.len
},
next:function() {
if(!this.hasNext()) {
return null
}
var i = this.current
this.current++
return this.data[i]
}
}
}
var it = iterator(datas)
var a1=null,a2=null
while(it.hasNext()) {
if(a1 == null) {
a1 = it.next()
}
a2 = it.next()
if(a2 == null) {
break
}
if(a1[0] instanceof Array) {
a1=merge2(a1,a2)
}else{
a1 = merge1(a1,a2)
console.log(a1)
}
}
console.log(a1)