假设我有以下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...发布于 2017-08-15 23:33:23
简单地循环其中一个,输出每个数组的索引。为此,需要在循环内部使用循环,对每个循环使用不同的索引:
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.");
希望这会有帮助!)
发布于 2017-08-15 23:30:55
只是为了计算?这很简单。
把它们相乘。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>');
}
}
}
https://stackoverflow.com/questions/45702972
复制相似问题