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

碎片时间学编程「286]:生成指定范围内的随机整数数组

2023-03-15 12:19 作者:路条编程  | 我要投稿


生成指定范围内的随机整数数组。

  • 使用Array.from()方法创建特定长度的空数组。

  • 使用Math.random()方法生成随机数并将它们映射到所需的范围,用Math.floor()方法使它们成为整数。

JavaScript

const randomIntArrayInRange = (min, max, n = 1) =>  Array.from(    { length: n },    () => Math.floor(Math.random() * (max - min + 1)) + min  );

示例:

randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]

更多内容请访问我的网站:https://www.icoderoad.com


碎片时间学编程「286]:生成指定范围内的随机整数数组的评论 (共 条)

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