我无法理解一段代码

I can't understand a piece of code

本文关键字:一段 代码      更新时间:2023-09-26

我在理解一个简单的概念时遇到了困难。代码下面:

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,因为他生成了01之间的值(1不包括在内),所以Math.floor(Math.random()*arr.length)不应该总是返回8在我的情况下?

这是我目前不明白的地方,我找不到任何关于这件事的资料。

谢谢。

Math.floor()返回小于或等于给定数字的最大整数。换句话说,它将一个数字四舍五入到最接近的整数。

在您的代码中,Math.random()*arr.length可以返回一个实数,因为Math.random可能返回。3,数组长度为8,因此,而不是随机数组元素为2.4,您将得到2,如果您想要能够选择数组元素的索引,这更有意义。如果Math.random()返回0.5,那么您将得到一个整数,但在大多数情况下,您可能不会得到一个整数。

打破Math.floor(Math.random()*arr.length):

  • arr.length is 8
  • Math.random()返回从0到但不包括1的值。
  • Math.floor将结果舍入8次Math.floor down
  • 使用.3作为Math.random()返回值的示例:
    Math.floor( .3 * 8)
    Math.floor(2.4)
    2

因此,给定代码Math.floor(Math.random()*arr.length),您将最终得到一个从0到7的整数,其中任何一个都可以用来选择arr数组中的项目,如arr[randomArr].