前两天工作中用到笛卡儿积,一时间没有思路,在网上找个一个很不错的方法特记录分享如下:
function cartesianProductOf() {
return Array.prototype.reduce.call(
arguments,
(total, currItem) =>{
var ret = [];
total.map((tol)=>{
currItem.map((curr)=>{
ret.push(tol.concat([curr]))
})
})
return ret;
},
[ [] ]
);
}
let res = cartesianProductOf([1,2],[3,4]);
console.log(res);
仅供参考!