Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random words in JavaScript? [duplicate]

Possible Duplicate:
Getting a random value from a JavaScript array

OK, so I have three variables here, each being rock, paper or scissors. Using JavaScript, how can I generate one of those words randomly?

So far it's like so:

<!DOCTYPE html>
<html>
    <body>
        <button type="button" onclick="myFunction()"> Click me</button>

        <script>
            function myFunction()
            {
                var c="Rock";
                var d="Paper";
                var e="Scissors";
            }
        </script>
    </body>
</html>

Then I'll have a variable called K, which will be the random word out of rock paper or scissors. So it'll be like so:

alert("The computer chose: " + k);

So how can I make JavaScript select randomly between the three variables, c, d and e?

like image 766
Logan545 Avatar asked Nov 05 '12 17:11

Logan545


2 Answers

Use:

var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
alert('The computer chose:' + thing);

Demonstration


Just to precisely answer your question, supposing you really want to keep your three global variables, you could do this:

var c = "Rock";
var d = "Paper";
var e = "Scissors";
var thing = window['cde'.charAt(Math.floor(Math.random()*3))];
document.write('The computer chose: ' + thing);

Demonstration

(But don't.)

like image 105
Denys Séguret Avatar answered Sep 18 '22 23:09

Denys Séguret


You can use Math.random() to get a random number beteween 0 and 1.

If you want a whole random number between 0 and 2. (so: 0, 1 or 2). You can use:

Math.floor(Math.random()*3);

Note that Math.round (instead of floor) would be wrong here since the edge values will have a lower chance, and you might actually get 3 as well.

like image 31
Halcyon Avatar answered Sep 18 '22 23:09

Halcyon