码迷,mamicode.com
首页 > 编程语言 > 详细

js编写一个数组笛卡尔积算法

时间:2018-04-28 15:47:58      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:ice   turn   product   ntp   ons   int   for   钻石   笛卡尔积   

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编写一个数组笛卡尔积算法

标签:ice   turn   product   ntp   ons   int   for   钻石   笛卡尔积   

原文地址:https://www.cnblogs.com/saving/p/8967631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!