multiCartesian (specs) { // 判断是否传递了参数,是否是空数组 if (!specs || specs.length === 0) { return [] } else { return joinSpec([[]], specs, 0, specs.length - 1) } // prevProducts 和 specs 两个数组做笛卡尔积 // i 是索引,表示原始数组遍历的位数 // max 是原始数组最大的长度 -1 function joinSpec (prevProducts, specs, i, max) { var currentProducts = [] var currentProduct var currentSpecs = specs[i] if (i > max) { return prevProducts } // 前面的数组 和 紧跟着后面的数组 做笛卡尔积 prevProducts.forEach(prevProduct => { currentSpecs.forEach(spec => { currentProduct = prevProduct.slice(0) currentProduct.push(spec) currentProducts.push(currentProduct) }) }) // 递归处理,前面笛卡尔积之后的结果作为前面的数组,然后循环往前推进1位 return joinSpec(currentProducts, specs, ++i, max) } }
原文:https://www.cnblogs.com/lizqhngs/p/12715083.html