2017-08-16 87 views
-1

我正在制作一套服装随机发生器。但我想添加一些规则来防止穿白色衬衫上的白色领带等怪异衣服。或图形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); 

我知道这与如果的和别人的,但我不知道该怎么做。

请原谅我的JS文盲。我学会了它,但从未真正使用它。到现在。

感谢

+0

仅供参考:你不能在这里喊特定的用户。 @符号仅适用于有人评论或发布到此特定问题或首先回答此问题,并且您在回应他们。如果有人评论或发布了其他问题(您的或其他人的问题),则此功能无效。 –

回答

1

有severals这样做的方法,这是我的建议:

您可以根据随机衬衫的结果

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

或者您可以使用减少方法是类似的 - >https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

如果你不太了解这些方法,看这个播放列表,它会帮助很多 - >https://www.youtube.com/watch?v=BMUiFMZr7vk&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84

相关问题