最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Function that randomly returns one of three options, where all options have the exact same chance? - Stack Overflow

programmeradmin0浏览0评论

I know this may have been asked before, but I'm trying to have a Javascript function return one of three options. The problem is the chance for each option should be pletely equal. This is what I have so far:

var choice = Math.random();
if (choice <= 0.34) {
    choice = "option1";
} else if (choice <= 0.67) {
    choice = "option2";
} else {
    choice = "option3";
}

This is already pretty accurate, however the probability of "option3" is slightly lower. How can I reformulate this to have each option have the same chance of occuring? I would prefer a solution that doesn't involve using "0.3333333333333333..." in the if condition or something like that.

I know this may have been asked before, but I'm trying to have a Javascript function return one of three options. The problem is the chance for each option should be pletely equal. This is what I have so far:

var choice = Math.random();
if (choice <= 0.34) {
    choice = "option1";
} else if (choice <= 0.67) {
    choice = "option2";
} else {
    choice = "option3";
}

This is already pretty accurate, however the probability of "option3" is slightly lower. How can I reformulate this to have each option have the same chance of occuring? I would prefer a solution that doesn't involve using "0.3333333333333333..." in the if condition or something like that.

Share Improve this question asked Jan 15, 2015 at 13:17 MoritzLostMoritzLost 2,8292 gold badges20 silver badges33 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

I think it would be cleaner and simpler to do something like this:

var options = ["option1", "option2", "option3"];
var choice = options[Math.floor(Math.random()*options.length)];

basicaly its your + Alex´s solution but i find that more beautiful

options=['option1','option2','option3']
choice = options[Math.floor(Math.random()*options.length)]

Multiplying the random number by 3 will allow you to do this without using decimals or fractions:

var choice = Math.random() * 3;
if (choice <= 1) {
    choice = "option1";
} else if (choice <= 2) {
    choice = "option2";
} else {
    choice = "option3";
}

Try this hard style:

var choice = ['first', 'second', 'third'][Math.floor(Math.random()*3)]

In my opinion the

var choice = ['first', 'second', 'third'] [Math.floor(Math.random()*3) +1]

plus 1 will get him random number from 1 to 3 only 3 multiplication we get number from 0 to 2.

but as array start from 0 to length -1 that why

var choice = ['first', 'second', 'third'][Math.floor(Math.random()*3)]

is right we need number from 0 to 2.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论