js编写一个数组笛卡尔积算法
Posted 狂乱贵公子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js编写一个数组笛卡尔积算法相关的知识,希望对你有一定的参考价值。
function getProducts(specs) { if (!specs || specs.length == 0) { return []; } else { return joinSpec([[]], specs, 0, specs.length-1); } 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); }); }); return joinSpec(currentProducts, specs, ++i, max); } }
var specs = [[{"spec_name":"颜色","spec_type":"1","spec_id":"5","spec_value_id":"11","spec_value_name":"白色"},{"spec_name":"颜色","spec_type":"1","spec_id":"5","spec_value_id":"12","spec_value_name":"黑色"}],[{"spec_name":"尺码","spec_type":"0","spec_id":"6","spec_value_id":"9","spec_value_name":"10"},{"spec_name":"尺码","spec_type":"0","spec_id":"6","spec_value_id":"10","spec_value_name":"20"}],[{"spec_name":"材质","spec_type":"0","spec_id":"7","spec_value_id":"13","spec_value_name":"钻石"},{"spec_name":"材质","spec_type":"0","spec_id":"7","spec_value_id":"14","spec_value_name":"水晶"},{"spec_name":"材质","spec_type":"0","spec_id":"7","spec_value_id":"15","spec_value_name":"玛瑙"}]];
console.log(getProducts(specs));
以上是关于js编写一个数组笛卡尔积算法的主要内容,如果未能解决你的问题,请参考以下文章