碎片时间学编程「340]:从数组中获取一个随机元素

从数组中获取一个随机元素。 使用 Math.random() 方法生成随机数。 将其乘以 Array.prototype.length 方法并使用 Math.floor() 方法将其四舍五入为最接近的整数。 此方法也适用于字符串。
JavaScript
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
示例:
sample([3, 7, 9, 11]); // 9
更多内容请访问我的网站:https://www.icoderoad.com