# JavaScript 笛卡尔积运算

## 笛卡尔积的函数

/**
* 二维数组的笛卡尔积
* @param specs 二维数组，需要做笛卡尔积运算的数组
* @returns {Array}
*/
function multiCartesian(specs) {
// 判断是否传递了参数，是否是空数组
if (!specs || specs.length == 0) {
return [];
} else {
return joinSpec([[]], specs, 0, specs.length - 1);
}

// prevProducts 和 specs 两个数组做笛卡尔积
// i 是索引，表示原始数组遍历的位数
// max 是原始数组最大的长度
function joinSpec(prevProducts, specs, i, max) {
var currentProducts = [], currentProduct, currentSpecs = specs[i];
if (i > max) {
return prevProducts;
}
// 前面的数组 和 紧跟着后面的数组 做笛卡尔积
prevProducts.forEach(function (prevProduct) {
currentSpecs.forEach(function (spec) {
currentProduct = prevProduct.slice(0);
currentProduct.push(spec);
currentProducts.push(currentProduct);
});
});
// 递归处理，前面笛卡尔积之后的结果作为前面的数组，然后循环往前推进1位
return joinSpec(currentProducts, specs, ++i, max);
}
}

var originArray = [[111,222,333],['aaa','bbb','ccc'],['*****','++++++']];

console.dir(multiCartesian(originArray))


### 结果

[[111,"aaa","*****"],[111,"aaa","++++++"],[111,"bbb","*****"],
[111,"bbb","++++++"],[111,"ccc","*****"],[111,"ccc","++++++"],
[222,"aaa","*****"],[222,"aaa","++++++"],[222,"bbb","*****"],
[222,"bbb","++++++"],[222,"ccc","*****"],[222,"ccc","++++++"],
[333,"aaa","*****"],[333,"aaa","++++++"],[333,"bbb","*****"],
[333,"bbb","++++++"],[333,"ccc","*****"],[333,"ccc","++++++"]]


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120