How to generate random words in JavaScript?
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.