如何从数组中获取随机结果,然后根据该结果从另一个数组中获取另一个随机结果?

时间:2017-12-01 19:02:03

标签: javascript jquery arrays random

我有一个数组

firstArray = [ "Blue", "Red", "Green" ];

Red

我想点击一个按钮并显示该数组的随机结果,让我们说它是“红色”。然后基于该结果“红色”我想点击第二个按钮并从另一个数组获得另一个随机结果。

blueArray = [ "Sky", "Water", "Jeans" ];
redArray = [ "Apple", "Firetruck", "Rose" ];
greenArray = [ "Grass", "Money", "Leaves" ];

Red - Rose

然后我想再次点击第一个按钮,获得一个新结果并清除第二个按钮的结果。

1 个答案:

答案 0 :(得分:1)

您可以将三个数组分组到一个对象中,该对象的键位于第一个数组中:

var colors = [ "Blue", "Red", "Green" ];                     // colors (keys from items object)

var items = {                                                // each color from colors has an array of items in this object
  "Blue": ["Sky", "Water", "Jeans"],                         // items for color "Blue"
  "Red": ["Apple", "Firetruck", "Rose"],                     // ...
  "Green": ["Grass", "Money", "Leaves"]                      // ...
};


var color = null;                                            // should be here in the outside so it will be accessed by both event listeners (you can initialize it to a color if you want)
$("#first-button").click(function() {                        // when clicking the first button ...
  color = colors[Math.floor(Math.random() * colors.length)]; // ... choose a random color from colors and assign it to the variable color
  $("#color-span").text(color);                              // set the text of the color span
});
$("#second-button").click(function() {                       // when clicking the second button ...
  if(color) {                                                // check if we had chosen a color (using the first button)
    var item = items[color][Math.floor(Math.random() * items[color].length)]; // then choose an item from the equivalent array (if color is "Blue" then items.Blue will be chosen)
    $("#sentence-span").text(color + " " + item);            // set the text of the sentence span (using both color and item
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first-button">First Button</button>
<button id="second-button">Second Button</button>
<p><b>Color is: </b><span id="color-span"></span></p>
<p><b>Sentence is: </b><span id="sentence-span"></span></p>