use*_*993 0 javascript random math
我在理解一个简单的概念时遇到了问题.代码下方:
var arr = [1, 3, 7, 9, 12, 5, 4, 6];
var randomArr = Math.floor(Math.random()*arr.length);
console.clear();
console.log(randomArr);
Run Code Online (Sandbox Code Playgroud)
我不明白这一点,为什么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可能会返回.3并且数组长度为8,所以不是随机数组元素是2.4,你将获得2,如果你想能够选择数组元素的索引.如果Math.random()返回.5,那么你会得到一个整数,但可能性是你在大多数情况下都不会得到一个整数.
打破Math.floor(Math.random()*arr.length):
arr.length 是8Math.random() 返回0到0但不包括1的值.Math.floor将结果Math.floor向下舍入8次.3返回值的示例Math.random():Math.floor( .3 * 8)Math.floor(2.4)2因此,给定代码,Math.floor(Math.random()*arr.length)您将得到一个从0到7的整数,然后可以使用其中任何一个来选择arr数组中的项目,如arr[randomArr].