javascript - 这种随机数生成方法背后的逻辑是什么?
问题描述
我正在查看一些代码高尔夫,并通过这种方式在 JavaScript 中生成随机数:
console.log(new Date % 100);
这会生成一个随机数 0-100,但是我无法理解它......我们不只是在做一个纪元时间的模数吗?这不会是 0-100 的值。
解决方案
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>
推荐阅读
- dask - 为什么对从 Parquet 文件构建的 Dask DataFrame 进行分类会大大增加其大小?
- python - 从数据框中获取一列以将其写入 csv 文件
- java - 如何在另一个类中引用常量的枚举方法
- r - POSIXct 日期对象被 apply() 转换
- javascript - JS类中的方法没有一个函数
- android - 无法在 Mac Visual Studio 中为 Xamarin Forms Android 创建发布存档
- flutter - 颤振 - 使用 image_picker 处理方法调用和 already_active 异常失败
- python-sphinx - Sphinx Autodoc 输出顺序
- intellij-idea - 如何在 IntelliJ IDEA 中隐藏此栏
- python - 使用循环减少代码并使用 tkinter 删除图像