javascript或jquery中唯一一对3个或更多数组

时间:2016-04-21 15:17:23

标签: javascript jquery arrays

我有一个类似

的数组
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解决方案。 所有组合都必须是独一无二的,需要以相同的方式打印。

2 个答案:

答案 0 :(得分: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/>');
    })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="res"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

纯JavaScript解决方案:

&#13;
&#13;
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>');
&#13;
&#13;
&#13;