Math.floor(Math.random()) +1 实际上做了什么
Math.floor(Math.random()) what does +1 actually do?
当你Math.floor(Math.random()*10)+1
它应该从我的理解中选择一个 1-10 之间的随机数。
但是,当我将+1
更改为更高或更低的任何数字时,1
我得到相同的结果。这是为什么呢?+1
到底是什么意思?
+1
偏移量。
通常您可以使用:
Math.floor(Math.random() * N) + M
这将生成介于 M 和 M + N - 1 之间的值。
演示小提琴
Math.random()
生成一个介于 0 和 1 之间的随机数。
因此,Math.random()*10
生成一个介于 0 和 10 之间的随机数,并(Math.random()*10)+1
一个介于 1 和 11 之间的数字。
Math.floor()
删除此数字的小数,并使其成为 0 到 10 之间的整数。
您可以在此处看到逻辑的顺序进展
整数介于 1 和 10 之间
- Math.random() 生成介于 0 和 1 之间的数字(有许多小数位)。
等:math.random() [随机返回 : 0.19157057767733932]
(这个数字仍然有很多小数位)
要获得随机整数,您需要将随机生成的数字乘以 10。
等
math.random()*10 =[随机返回 : 2.9757621488533914]
- 由于该数字仍然有许多小数位,因此请使用 floor() 方法将数字向下/最接近的整数四舍五入,这将给 u 一个介于 0 和 9 之间的值。然后,您可以添加 1 使其成为介于 1 和 10 之间的数字。
等:
数学地板(0.6) [返回 0 ]
数学地板(0.6)+ 1 [返回 1 ]
基本:
(random() >= 0)
总是true
(random() < 1)
总是true
(Math.floor(random()) == 0)
总是true
最大:
(Math.floor(random() * 10) >= 0)
总是true
(Math.floor(random() * 10) < 10)
总是true
最低:
(Math.floor(random() * 10) + 1 >= 1)
总是true
(Math.floor(random() * 10) + 1 < 11)
总是true
最大回合数:
(Math.round(random() * 10, 0) >= 0)
总是true
(Math.round(random() * 10, 0) <= 10)
总是true
- 这是什么 ==- javascript 运算符
- 我的单元测试选项是什么
- 全局变量和全局对象的属性之间有什么区别吗
- 打破承诺链的好方法是什么
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Javascript中的空白是什么
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- 在ember/handlers中使用value和valueBinding有什么区别
- 什么'在webpack外部设置中,reactDom和reactDom不同
- 在JavaScript中拆分日期字符串的更好方法是什么
- 为什么$.brower被弃用?还有什么更好的替代方案
- 什么是&&在没有if的行中的变量之间
- Math.min()和Math.max()之间有什么区别?在Javascript中
- 为什么当我们把Math.floor写成HTML angular时,它什么也不返回
- Math.floor(Math.random()) +1 实际上做了什么
- Math.max方法背后的逻辑是什么
- Math.floor math.random (+ min 在做什么)
- 我应该使用什么而不是扩展操作符Chrome在Math.max(..arr)
- 我的Math max函数出了什么问题
- Javascript Math.cos和Math.sin不准确.有什么解决办法吗