【发布时间】:2017-09-02 04:24:36
【问题描述】:
我使用在此站点上找到的代码来访问字符串值数组。我更改了变量名,但除此之外,代码保持不变。
var rand = array[Math.floor(Math.random() * array.length)];
它有效,据我了解,(Math.random() * array.length) 是本身生成随机数的区域,那么为什么需要Math.floor?我显然不明白这里很明显的东西。
【问题讨论】:
-
Math.random返回一个浮点数,数组元素索引实际上是整数。Math.floor将浮点数向下舍入到最接近的整数。
标签: javascript arrays math random floor