我在理解一个简单的概念时遇到了问题。代码如下:
var arr = [1, 3, 7, 9, 12, 5, 4, 6];
var randomArr = Math.floor(Math.random()*arr.length);
console.clear();
console.log(randomArr);
我不明白的是为什么 Math.floor(Math.random()*arr.length)
每次返回一个随机数 Math.floor(Math.random())
总是返回0
?据我了解,Math.floor(Math.random())
将始终返回 0
因为他生成了 0
之间的值和1
( 1
不包括在内),所以不应该 Math.floor(Math.random()*arr.length)
总是返回8
就我而言?
这是我目前不明白的地方,也找不到任何关于此事的信息。
谢谢。
最佳答案
Math.floor()
返回小于或等于给定数字的最大整数。换句话说,它将数字向下舍入到最接近的整数。
在您的代码中,Math.random()*arr.length
可能会返回一个实数,因为 Math.random
可能会返回 0.3 并且数组长度为 8,因此您将得到 2,而不是随机数组元素 2.4,如果您希望能够选择数组元素的索引,这更有意义。如果 Math.random()
返回 0.5,那么您将得到一个整数,但在大多数情况下您可能不会得到整数。
打破Math.floor(Math.random()*arr.length)
:
arr.length
为 8Math.random()
返回 0 到 1 之间的值(但不包括 1)。Math.floor
将Math.floor
的结果向下舍入 8 次- 使用
.3
作为Math.random()
返回值的示例:
Math.floor( .3 * 8)
Math.floor(2.4)
2
因此,给出代码 Math.floor(Math.random()*arr.length)
你最终会得到一个从零到七的整数,然后可以使用其中的任何一个来选择arr
数组中的一个项目,例如 arr[randomArr]。
关于javascript - 一段代码看不懂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40468481/