欢迎光临散文网 会员登陆 & 注册

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

2023-06-09 12:41 作者:路条编程  | 我要投稿


从数组中获取一个随机元素。 使用 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


碎片时间学编程「340]:从数组中获取一个随机元素的评论 (共 条)

分享到微博请遵守国家法律