商品多規格模型構造示例

weixin_33816946發表於2016-05-30

系統涉及到商品,往往就有規格的存在,一個商品多個規格需要去維護,如何通過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>

 

示例:

相關文章