首页 > 解决方案 > 这种随机数生成方法背后的逻辑是什么?

问题描述

我正在查看一些代码高尔夫,并通过这种方式在 JavaScript 中生成随机数:

console.log(new Date % 100);

这会生成一个随机数 0-100,但是我无法理解它......我们不只是在做一个纪元时间的模数吗?这不会是 0-100 的值。

标签: javascript

解决方案


It depends, it takes the remainder (0-99) of the time value in milliseconds, which is semi-random (as in: not very predictable) if used only once. It will generate linear sequences with duplicates if run in a tight loop.

Demo:

function show(count) {
  console.clear();
  for (var i = 0; i < count; i++)
    console.log(new Date % 100);
}
<button onclick="show(1)">Show 1</button>
<button onclick="show(20)">Show 20</button>


推荐阅读