【问题标题】:How to add custom rules to a calculator?如何将自定义规则添加到计算器?
【发布时间】:2017-08-16 01:01:58
【问题描述】:

我正在制作服装随机化器。但我想为其添加一些规则,以防止出现奇怪的服装,例如白衬衫上的白色领带。或图形 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 和 else 完成的,但我不知道如何。

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

谢谢

【问题讨论】:

  • 仅供参考:您不能在这里向特定用户大喊大叫。 @ 符号仅在有人评论或发布此特定问题或首先回答此问题并且您正在回复他们时才有效。如果有人评论或发布了不同的问题(您的或其他人的),则此方法无效。

标签: javascript random combinations permutation calculator


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2014-02-05
    • 2014-10-30
    • 2018-03-22
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多