我正在制作一套装备随机发生器。但是我想为它添加一些规则来防止像白衬衫上的白色领带那样奇怪的服装。或任何图形T恤上的领带。或者在衬衫上穿高领毛衣。
到目前为止,这是代码:
var shirts = ["White", "navy", "light blue", "gray"];
var pants = ["black", "navy", "gray"];
var ties = ["red and blue squares", "purple", "white", "red"];
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( " shirt: " + random_shirt + " pants: " + random_pants + " tie: " + random_tie);
我知道它已经完成了if和其他,但我不知道如何。
请原谅我的JS文盲。我学到了它但从未真正使用它。到现在为止。
由于
答案 0 :(得分:1)
有几种方法可以做到这一点,这是我的建议:
您可以根据随机衬衫的结果过滤裤子阵列
var random_shirt = [random logic];
/*
This will iterate over your pants array, returning a filtered array
with containing the items that returned true
item: the actual item
index: index of the actual item
array: original array
*/
filtered_pants = pants.filter(function(item, index, array) {
if (item == random_shirt) {
// This item won't be in the filtered array
return false;
}
if ([another custom rule]) {
return false;
}
/*
After passing all the rules return true to include this item in
the filtered array
*/
return true;
});
// Now shuffle over the filtered array
var random_pants = filtered_pants[Math.floor(Math.random()*pants.length)];
然后用领带重复它
请务必了解过滤方法的文档 - > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
或者你可以使用类似的reduce方法 - > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
如果您不太了解这些方法,请观看此播放列表,它会给您带来很多帮助 - > https://www.youtube.com/watch?v=BMUiFMZr7vk&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84