Why JavaScript Math.random() returns same number multiple times

前端 未结 2 618
梦如初夏
梦如初夏 2021-01-17 08:55

I have an array with two items and I need to random a choice of this items but the most of times I get the same item from array...

See the code:

var          


        
2条回答
  •  -上瘾入骨i
    2021-01-17 09:48

    The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.

    Math.random() * 2 will give range 0 to 1.99999999999999 but not 2. Math.floor(0...1.999999999999) will either return 0 or 1 with 50% chance similar to a coin.

    numbers[0] will give 523 and numbers[1] will give 3452

提交回复
热议问题