简体   繁体   中英

Javascript! How do I choose a random array WITH a random array?

Here's what I'm trying to do. I just got this random concoction to work after spending 3 hours at http://www.w3schools.com/js/

<!DOCTYPE html>
<html>
<body>

<p>Loopin through an array using a for loop:</p>

<p id="demo"></p>

<script>

var myShows = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men',
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

var show = myShows[Math.floor(Math.random() * myShows.length)];

document.getElementById("demo").innerHTML = show




</script>
<input type="button" value="Refresh Page" onClick="window.location.reload()">
</body>
</html>

How could I make a random generator to randomly pull from two or more lists? How would I make it do it on certain reuslts?

The outcome Im looking for: Instead of 1 random result per click,

I click once, and it 1. runs through and array of "shows, cartoons, theatre"

If the result is shows, THEN RANDOMLY generate one of the show results If the result is cartoons, Then Randomly generate a cartoon result If the results is Theatre, Then Randomly Generate a theatre result

Shows = "bob newhard, mr.blevedere, growing pains"
cartoons = "chowder, flapjack, voltron"
Thearte = "Phantom of the opera, Lion king, Roots"

How would I do this Array, on an array?

Explanation

I would use a 2D array - this practically is an array, where each item is another array. You can have arrays with as many "dimensions" as you want, but here two is what we want.

So, your array would be:

var genres = [["bob newhard","mr.blevedere","growing pains"],["chowder","flapjack","voltron"],["Phantom of the opera","Lion king","Roots"]]

Now, I would randomly select a sub-array from genres . Lets do it like so:

var shows = genres[Math.floor(Math.random()*genres.length)]

Now, we just need to select a random item from that array. This is practically the same code, except we replace genres with shows :

var show = shows[Math.floor(Math.random()*shows.length)]

Solution

(You'll need to click the button to generate a show the first time)

 function newshow() { var genres = [["bob newhard","mr.blevedere","growing pains"],["chowder","flapjack","voltron"],["Phantom of the opera","Lion king","Roots"]]; var shows = genres[Math.floor(Math.random()*genres.length)]; var show = shows[Math.floor(Math.random()*shows.length)]; document.getElementById("show").innerHTML = show; }
 <button onclick="newshow()">New Show!</button><br> <div id="show"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM