2016-04-21 50 views
0

我有這樣唯一的對3個或更多陣列的JavaScript或jquery的

main['device']=['iphone4','iphone5','iphone6']; 
main['color']=['red','blue','white']; 
main['size']=['10','20','30']; 

所有3個數組的數組。是動態的。 我需要像所有組合

iphone4 red 10 
iphone4 red 20 
iphone4 red 30 
iphone4 blue 10 
iphone4 blue 10 
iphone4 blue 30 
iphone4 white 10 
iphone4 white 30 
iphone4 white 30 


iphone5 red 10 
iphone5 red 20 
iphone5 red 30 
iphone5 blue 10 
iphone5 blue 10 
iphone5 blue 30 
iphone5 white 10 
iphone5 white 30 
iphone5 white 30 


iphone6 red 10 
iphone6 red 20 
iphone6 red 30 
iphone6 blue 10 
iphone6 blue 10 
iphone6 blue 30 
iphone6 white 10 
iphone6 white 30 
iphone6 white 30 

JavaScript或jQuery解決方案,如果可能的話。 所有組合都需要獨一無二,並且需要以相同的方式打印。

+0

什麼是你現在需要做的這個代碼中的問題? –

+1

是不規則的藍色和白色的錯字..?否則一個3嵌套'forEach()'會直接做... – Redu

回答

0

純JavaScript解決方案:

var main = new Array([]); 
 
    
 
main['device']=['iphone4','iphone5','iphone6']; 
 
main['color']=['red','blue','white']; 
 
main['size']=['10','20','30']; 
 

 
var res = []; 
 
main['device'].forEach(function (device) { 
 
    main['color'].forEach(function(color) { 
 
    main['size'].forEach(function(size) { 
 
     res.push([device, color, size].join(' ')); 
 
    }) 
 
    }); 
 
    res.push(''); 
 
}); 
 

 

 
document.body.innerHTML = res.join('<br>');

0

這是您想要的代碼。我希望它有幫助。

var main = new Array([]); 
 
    
 
    main['device']=['iphone4','iphone5','iphone6']; 
 
    main['color']=['red','blue','white']; 
 
    main['size']=['10','20','30']; 
 
    
 
    $.each(main['device'], function(index, value){ 
 
     var device = value; 
 
     $.each(main['color'], function(index2, value2) { 
 
     var color = value2; 
 
     $.each(main['size'], function(index3, value3) { 
 
      var size = value3; 
 
      var res = value + " " + value2 + " " + value3; 
 
      $('#res').append(res); 
 
      $('#res').append('<br/>'); 
 
     }) 
 
     
 
     }) 
 
     $('#res').append('<br/>'); 
 
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="res"></div>

相關問題