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
?
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With