我正在尝试使用 JavaScript 创建一个随机数,如下所示
function valid(form) {
var input = 0;
var input = document.getElementById('custom1').value;
var final_input = input.charAt(0);
var number = 1000000000 - Math.floor(Math.random() * 1000000000);
final_input = final_input + number;
document.getElementById('custom4').value = final_input;
}
这个想法是,它将从“custom1”(这是输入字段之一)获取值,然后获取第一个字符。之后,它将添加接下来的 9 个随机数字,并将最终值放入表单的 custom4(另一个输入字段)中。到目前为止,JavaScript 运行良好。但是,我宁愿让随机数字与当前时间一起播种。我认为这将是非常随机的。这可能吗?
最佳答案
JavaScript standard random API不支持显式播种(这是一个遗憾)。这是the spec :
Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.
如果您确实需要使用给定的数字为生成器提供种子,则必须使用类似 this one 的库。 (未经我测试)。
但是 JavaScript 随机 API 是隐式播种的,这确保您会得到不同的结果。没有关于如何播种的 ECMAScript 规范,但很可能所有浏览器都使用该时间进行播种。 MDN 说
The random number generator is seeded from the current time, as in Java.
关于javascript - 使用自定义时间播种的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18696779/