返回数组中的随机元素

5年以前  |  阅读数:363 次  |  编程语言:JavaScript 

返回数组中的随机元素。

使用Math.random()生成一个随机数, 将它与length相乘, 并使用数学将其舍入到最接近的整数Math.floor()。此方法也适用于字符串。

const sample = arr => arr[Math.floor(Math.random() * arr.length)];
// sample([3, 7, 9, 11]) -> 9

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8