/**
* 根据Array生成笛卡尔积
* @param var specObj {"规格名1":["规格值A","规格值B"],"规格名2":["规格值W","规格值N"]...}
* @return [{"规格名1":"规格值1"},{"规格名2":"规格值2"}...]
* @note 多维数组依次去匹配(利用层次关系,0索引数组遍历后 -> 1索引数组再遍历依次递增)
*/
function cartesian(specObj)
{
let result = [];
let level = [];
let loop = 1;//循环总次数
for(let name in specObj)
{
level.push({"name":name,"index":0,"list":specObj[name]})
loop *= specObj[name].length;
}
for(let i = 0; i < loop; i++)
{
let temp = {};
for(let le in level)
{
let index = level[le].index;
let name = level[le].name;
temp[name] = level[le].list[index];
}
result.push(temp);
//底层索引+1
level[0].index++;
for(let le = 0; le < level.length; le++)
{
//循环下个级别
if(level[le].index == level[le].list.length)
{
let nextLevel = le + 1;
if(nextLevel <= level.length - 1)
{
level[nextLevel].index++;
//之前子集都要置空
for(let child = 0; child < nextLevel; child++)
{
level[child].index = 0;
}
}
}
}
}
return result;
}