首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算不同数组之间的所有组合?

如何计算不同数组之间的所有组合?
EN

Stack Overflow用户
提问于 2017-08-15 23:28:09
回答 2查看 203关注 0票数 0

假设我有以下3个数组:

代码语言:javascript
复制
 Shirts [White, Navy, Light Blue, Gray],
 Pants [Black, Navy, Gray],
 Ties [Houndstooth, Polka Dot, Herringbone, Solid]

我该怎么做才能得到这个结果?

代码语言:javascript
复制
 White Shirt with Black Pants and a Houndstooth Tie,
 White Shirt with Black Pants and a Polka Dot Tie,
 White Shirt with Black Pants and a Herringbone Tie,
 White Shirt with Black Pants and a Solid Tie,

 White Shirt with Navy Pants and a Houndstooth Tie,
 White Shirt with Navy Pants and a Polka Dot Tie,
 White Shirt with Navy Pants and a Herringbone Tie,
 White Shirt with Navy Pants and a Solid Tie,

 And so on,
 And so on...
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-15 23:33:23

简单地循环其中一个,输出每个数组的索引。为此,需要在循环内部使用循环,对每个循环使用不同的索引:

代码语言:javascript
复制
var shirts = ["White", "Navy", "Light Blue", "Gray"];
var pants = ["Black", "Navy", "Gray"];
var ties = ["Houndstooth", "Polka Dot", "Herringbone", "Solid"];

for (var i = 0; i < shirts.length; i++) {
  var start = shirts[i] + " shirt with ";
  for (var j = 0; j < pants.length; j++) {
    var middle = pants[j] + " pants and a ";
    for (var k= 0; k < ties.length; k++) {
      var end = ties[k] + " tie.<br />";
     document.write(start + middle + end);
    }
  }
}

只需将三个数组的.length相乘,将总和赋值给一个变量,然后输出该变量,就可以得到总数:

代码语言:javascript
复制
var shirts = ["White", "Navy", "Light Blue", "Gray"];
var pants = ["Black", "Navy", "Gray"];
var ties = ["Houndstooth", "Polka Dot", "Herringbone", "Solid"];
var total_combinations = shirts.length * pants.length * ties.length;
document.write("Total number of combinations: " + total_combinations);

要获得随机输出,可以在数组索引上结合使用Math.floor()Math.random(),如下所示:

代码语言:javascript
复制
var shirts = ["White", "Navy", "Light Blue", "Gray"];
var pants = ["Black", "Navy", "Gray"];
var ties = ["Houndstooth", "Polka Dot", "Herringbone", "Solid"];

var random_shirt = shirts[Math.floor(Math.random()*shirts.length)];
var random_pants = pants[Math.floor(Math.random()*pants.length)];
var random_tie = ties[Math.floor(Math.random()*ties.length)];

document.write(random_shirt + " shirt with " + random_pants + " pants and a " + random_tie + " tie.");

希望这会有帮助!)

票数 2
EN

Stack Overflow用户

发布于 2017-08-15 23:30:55

只是为了计算?这很简单。

把它们相乘。5*3*4=60变体

如果您需要将所有变体作为文本:

代码语言:javascript
复制
var shirts = ['White', 'Navy', 'Light Blue', 'Gray'];
    var pants = ['Black', 'Navy', 'Grey'];
    var ties = ['Houndstooth', 'Polka Dot', 'Herringbone', 'Solid'];
    
    for(var s in shirts) {
      for(var p in pants) {
        for(var t in ties) {
            document.write(shirts[s] + ' Shirt with ' + pants[p] + ' Pants and a ' + ties[t] + ' Tie<br>');
        }
      } 
    }

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45702972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档