2019-06-03
描述
从数组中返回一个随机元素。
提示
- 使用
Math.random()
和数组的长度相乘来生成随机数 - 使用
Math.floor()
进行四舍五入,从而使结果为最接近的整数 - 这个方法同样适用于字符串
代码
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
示例
随机返回数组中的一个元素:
sample([3, 7, 9, 11]);
2019-06-03
从数组中返回一个随机元素。
Math.random()
和数组的长度相乘来生成随机数Math.floor()
进行四舍五入,从而使结果为最接近的整数const sample = arr => arr[Math.floor(Math.random() * arr.length)];
随机返回数组中的一个元素:
sample([3, 7, 9, 11]);