商品多规格模型构造示例

系统涉及到商品,往往就有规格的存在,一个商品多个规格需要去维护,如何通过js的方式快速构造出商品规格编辑的排列组合?整体思想是逐个规格往下合并的方式,核心js代码如下:

<script type="text/javascript">
function test() {
                    var doubleArrays = [
                        [{valId:"1",valCode:"M",valName:"大码"},{valId:"2",valCode:"L",valName:"小码"}],   //规格1:尺码
                        [{valId:"3",valCode:"R",valName:"红色"},{valId:"4",valCode:"W",valName:"白色"}],  //规格2:颜色
                        [{valId:"5",valCode:"C",valName:"长"},{valId:"6",valCode:"D",valName:"短"}]  //规格3:长度
                    ];
                    var ret = doExchange(doubleArrays);
                    console.log(ret);
                    document.write("共有:" + ret.length + "种组合!<br/>");
                    for (var i = 0; i < ret.length; i++) {
                        document.write(ret[i] + "<br/>");
                    }
                }

                function doExchange(doubleArrays) {
                    var len = doubleArrays.length;
                    if (len >= 2) {
                        var len1 = doubleArrays[0].length;
                        var len2 = doubleArrays[1].length;
                        var newlen = len1 * len2;
                        var temp = new Array(newlen);
                        var index = 0;
                        for (var i = 0; i < len1; i++) {
                            for (var j = 0; j < len2; j++) {
                                temp[index] = {
                                    valId:doubleArrays[0][i].valId + "_" + doubleArrays[1][j].valId,
                                    valCode:doubleArrays[0][i].valCode + "_" + doubleArrays[1][j].valCode,
                                    valName:doubleArrays[0][i].valId + "_" + doubleArrays[1][j].valName
                                };
                                index++;
                            }
                        }
                        var newArray = new Array(len- 1);
                        newArray[0] = temp;
                        if (len > 2) {
                           var _count = 1;
                           for(var i=2;i<len;i++)
                           {
                               newArray[_count] = doubleArrays[i];
                               _count ++;
                           }
                        }
                        console.log(newArray);
                        return doExchange(newArray);
                    }
                    else {
                        return doubleArrays[0];
                    }
                }
      test() ;
      
      </script>

 

示例:

posted @ 2016-05-30 11:55  jackchain  阅读(1069)  评论(0编辑  收藏  举报