我正在尝试将旧的 C 标准库函数 rand()
移植到 JavaScript 中,仅作测试之用。我不打算在实际场景中使用,所以请不要担心其安全性问题。
这是该函数的 C 语言实现:
seed = seed * 1103515245 + 12345;
return (seed/65536) % 32768;
在这个例子中,32768 是 RAND_MAX
。因此,我尝试将其移植到 Javascript:
Random = function(p) {
this.s = p;
this.rand = function() {
this.s = this.s * 1103515245 + 12345;
return Math.floor((this.s / 65536) % 32768);
};
};
let r = new Random(Math.floor(new Date() / 1000));
console.log(r.rand()); // gives expected results
console.log(r.rand()); // second call produces 0
r.rand()
时,它会产生预期的结果。但是每次连续调用r.rand()
都只会给我返回0,我很好奇为什么...