如何计算不同数组之间的所有组合?
问题描述:
比方说,我有这样3个数组:如何计算不同数组之间的所有组合?
Shirts [White, Navy, Light Blue, Gray],
Pants [Black, Navy, Gray],
Ties [Houndstooth, Polka Dot, Herringbone, Solid]
我应该怎么做才能得到这样的结果
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...
答
只需遍历其中的一个,输出每个数组的索引。你需要使用这种循环的内部循环,使用不同的指标为每个循环:
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
一起获得总,总赋值给一个变量,并输出该变量:
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()
如下:
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.");
希望这有助于! :)
答
只是计算?这很容易。
乘以它们。 5*3*4=60
变体。
如果你需要将所有的变体文字:
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>');
}
}
}
我有点生锈的JS,所以请解释你做了什么。 – Ferrius
你有这个代码吗?如果不是,先写一些并尝试一下,然后我们会看到我们可以做些什么来帮助。 – jmoon
你的问题到底是什么?你有什么尝试?您发布的阵列有75种可能的组合。 – Thomas