+ 10

# how to pick a varible randomly in web

if i have three variables var a = "a" var b = "b" var c = "c" var rand = __randomly choosen from a,b,c__ ....please answer considering that i dont know anything about web page designing or JS...

6 Answers

+ 14

var arr = [a,b,c];
var rand = Math.floor(Math.random() * 3);
arr[rand];
What this code does is that it stores the variables in an array and we create a random number to randomly access one variable from the array. But if you want it to generate random no.s each time rather than only when a function is called, just do:
arr[Math.floor(Math.random() * 3)];
// no need to create the rand variable then

+ 11

@Suraj: It will remain the same because you are changing the value of the variable and not the variable name.
Note: arr[Math.floor(Math.random() * 3)];
In this line, the 3 is actually the length of the array so if the length is 50 or any other no. just replace 3 with that no.

+ 10

thanks man! You saved my day

+ 8

i wanted to ask you that what iff
a = "string1"
b = "string2"
c = "string3"
will the code still be same,
or it needs different code?

+ 8

simply Math.random() returns a value between 0 and 1 in decimal values eg. 0.67464627
To get a random no. between desired no. without decimal points use this :-
var r=Math.floor(Math.random()*max )+min;

+ 7

@Utkarsh Utkarsh, sorry, but if we would (for example) set min to 2 and max to 8 then we can get 10 with you code. May be this one will be better:
var r = Math.floor(Math.random()*(max-min))+min
?
or even:
var r = Math.floor(Math.random()*(max-min+1))+min
?