2016-08-31 79 views
0

我想根據顏色,大小等屬性生成產品可能具有的所有可能變體。我試圖實現由給出的solution profitphp在JavaScript中,但沒有得到所需的結果。Javascript:根據屬性計算產品變體的數量

下面是我實現的:

var data = [['red', 'blue', 'green'],['small', 'medium', 'large']]; 

result = generateVariants(data); 
console.log(result); 

function generateVariants(data,prefix) { 
    if (typeof prefix === 'undefined') { 
     prefix = ''; 
    } 

    var result = []; 
    var attribute = data.shift(); 

    $.each(attribute, function(key,val) { 
     if (data instanceof Array && data.length > 0) { 
      result = result.concat(generateVariants(data, val + ' ')); 
     } 
     else { 
      result.push(prefix + val); 
     } 
    }); 

    return result; 
} 

預期結果:

["red small", "red medium", "red large", "blue small", "blue medium", "blue large", "green small", "green medium", "green large"] 

相反,我得到這個:

["red small", "red medium", "red large", "blue", "green"] 

任何幫助是很大的讚賞。謝謝。

+2

您只需要計算輸入數組的笛卡爾乘積以獲得可能的組合。也許這個鏈接可以幫助。看看answer.http://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript –

+0

@Farooq謝謝你指着我在正確的方向。 – codeit

回答

1

不是傳遞原始陣列,克隆它並通過克隆陣列作爲參數。

var data = [['red', 'blue', 'green'],['small', 'medium', 'large']]; 

    result = generateVariants(data); 
    console.log(result); 

    function generateVariants(data,prefix) { 
     if (typeof prefix === 'undefined') { 
      prefix = ''; 
     } 

     var result = []; 
     var attribute = data.shift(); 

     $.each(attribute, function(key,val) { 
      if (data instanceof Array && data.length > 0) { 




       // Instead of passing the original array, clone it and pass the cloned array as argument. 
    _data = data.slice(0); 



       result = result.concat(generateVariants(_data, val + ' ')); 
      } 
      else { 
       result.push(prefix + val); 
      } 
     }); 

     return result; 
    } 
+0

它不超過2的數組元素工作。 – codeit