为什么JavaScript Math.random()多次返回相同的数字

Ita*_*lux -4 javascript math node.js

我有一个包含两个项目的数组,我需要随机选择这些项目,但大多数时候我从数组中得到相同的项目...

看代码:

var numbers = Array(523,3452);
var choice = numbers[Math.floor(Math.random()*numbers.length)];
console.log("Choice:", choice);
Run Code Online (Sandbox Code Playgroud)

我该如何避免这种行为?

Mar*_*yer 10

随机数可以出现在条纹中; 这是随机的一部分.但随着时间的推移,大数法则应该接管并消除这些条纹.您可以通过多次运行并计算来轻松测试:

var numbers = Array(523,3452);
let counts = [0,0]

for (let i = 0; i < 10000; i++) {
    let choice = numbers[Math.floor(Math.random()*numbers.length)];
    if (choice ===  523) counts[0]++
    else if (choice == 3452) counts[1]++
}

// counts should be about even
console.log(counts);
Run Code Online (Sandbox Code Playgroud)

  • 我第一次跑他们都是'5000`! (3认同)
  • *随机数可以出现在条纹中; 这是随机的一部分.* - 爱有时向业务解释. (2认同)
  • 哇,您实际上可以为此获得[reversal](https://stackoverflow.com/help/badges/95/reversal)徽章。 (2认同)