首页 > 解决方案 > 如何理解 JavaScript 'Math.floor(Math.random() *6)+1' 中的这个内置函数?

问题描述

如果我使用此代码:

Math.floor(Math.random() *6)

这会给我一个从 1 到 5 的随机数,对吗?

编写此代码是否相同:

Math.floor(Math.random() *6)+1

像这样?

Math.floor(Math.random() *7)

因为他们都会给我一个介于 1 到 6 之间的数字?

只是看一个教程,他没有解释这个功能,我很好奇他是否可以使用第二个例子而不是第一个例子。

标签: javascript

解决方案


不,它们不会是相同的(6 是最大值)Math.floor(Math.random() *6)+1之间的随机值。这个最小值始终是我们最后添加的值。1-6
11

Math.floor(Math.random() *7)是之间的随机值0-7


推荐阅读