题目如下:
const productSpecification = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
]
以上是商品规格阵列的初始化值,要求获得这些规格有多少种组合方式,并打印结果
思路: 通过从头到尾的顺序拼装方式进行组合
例如:第一组和第二组首先进行组合
[ [1, 4], [1, 5], [1, 6], [2, 4] ...]
然后使用一个值接收并继续将这个值传入下一次循环,对第三组进行拼接
具体代码如下:
const zuzhuang = (arr1, arr2) => {
let result = []
arr1.forEach(value1 => {
arr2.forEach(value2 => {
if (typeof value1 === "number") {
result.push([value1, value2])
} else {
let value3 = [...value1]
value3.push(value2)
result.push(value3)
}
})
})
return result
}
var initData = productSpecification[0]
productSpecification.forEach((n, index) => {
if (index != 0) {
initData = zuzhuang(initData, n)
}
})
console.log("initData:" + JSON.stringify(initData))
最终打印结果:
[[1,4,7,10],[1,4,7,11],[1,4,7,12],[1,4,8,10],[1,4,8,11],[1,4,8,12],[1,4,9,10],[1,4,9,11],[1,4,9,12],[1,5,7,10],[1,5,7,11],[1,5,7,12],[1,5,8,10],[1,5,8,11],[1,5,8,12],[1,5,9,10],[1,5,9,11],[1,5,9,12],[1,6,7,10],[1,6,7,11],[1,6,7,12],[1,6,8,10],[1,6,8,11],[1,6,8,12],[1,6,9,10],[1,6,9,11],[1,6,9,12],[2,4,7,10],[2,4,7,11],[2,4,7,12],[2,4,8,10],[2,4,8,11],[2,4,8,12],[2,4,9,10],[2,4,9,11],[2,4,9,12],[2,5,7,10],[2,5,7,11],[2,5,7,12],[2,5,8,10],[2,5,8,11],[2,5,8,12],[2,5,9,10],[2,5,9,11],[2,5,9,12],[2,6,7,10],[2,6,7,11],[2,6,7,12],[2,6,8,10],[2,6,8,11],[2,6,8,12],[2,6,9,10],[2,6,9,11],[2,6,9,12],[3,4,7,10],[3,4,7,11],[3,4,7,12],[3,4,8,10],[3,4,8,11],[3,4,8,12],[3,4,9,10],[3,4,9,11],[3,4,9,12],[3,5,7,10],[3,5,7,11],[3,5,7,12],[3,5,8,10],[3,5,8,11],[3,5,8,12],[3,5,9,10],[3,5,9,11],[3,5,9,12],[3,6,7,10],[3,6,7,11],[3,6,7,12],[3,6,8,10],[3,6,8,11],[3,6,8,12],[3,6,9,10],[3,6,9,11],[3,6,9,12]]