javascript, how to set a var to a certain value then change it randomly
i have this scri开发者_开发百科pt:
var randNum = Math.floor(Math.random() * 3);
if (randNum == 0){
alert ('0');
} else {
alert ('1');
}
and every time it runs i get a random value of 1 or 0
what i want is to always start the randNum
var as being 0
any ideas?
thanks
var randNum = null;
function getRand() {
if (randNum == null){
return randNum = 0;
}
return randNum = Math.round(Math.random());
}
now that will do it
http://jsfiddle.net/zYrS8/
or even more compact and unreadable:
var randNum = null;
function getRand() {
return randNum = (randNum == null?0:Math.round(Math.random()));
}
Maybe I don't understand your but give this a shot:
var randNum = 0;
function GetRandom()
{
if (randNum == 0){
alert ('0');
} else {
alert ('1');
}
randNum = Math.floor(Math.random() * 3);
}
GetRandom();
GetRandom();
GetRandom();
精彩评论