2017-08-16 133 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

相關問題