[zhongjyuan]常见随机函数

文章介绍了JavaScript中的三个实用函数:randomInt用于生成指定范围内的随机整数,randomString生成指定长度的随机字符串(可自定义字符排除和追加),randomColor则生成随机RGB颜色。每个函数都有详细的参数说明和示例应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

randomInt:生成指定范围内的随机整数

alt
/**
  * 生成指定范围内的随机整数
  * @param {number} min - 最小值(包含)
  * @param {number} max - 最大值(包含)
  * @returns {number} - 返回指定范围内的随机整数
  *
  * @example
  * console.log(randomInt(1, 10)); // 输出介于 1 和 10 之间的一个随机整数
  * console.log(randomInt(-5, 5)); // 输出介于 -5 和 5 之间的一个随机整数
  */

 randomIntfunction (min, max{
  return Math.floor(Math.random() * (max - min + 1) + min);
 },

randomString:生成指定长度的随机字符串

alt
 /**
  * 生成指定长度的随机字符串
  * @param {number} length - 字符串长度
  * @param {string[]} exclude - 要排除的字符数组(可选)
  * @param {string[]} append - 要追加的字符数组(可选)
  * @returns {string} - 返回生成的随机字符串
  *
  * @example
  * console.log(randomString(8)); // 输出一个包含大小写字母和数字的长度为 8 的随机字符串
  * console.log(randomString(10, ["a", "b"])); // 输出一个不包含字符 "a" 和 "b" 的长度为 10 的随机字符串
  * console.log(string(12, [], ["!", "@"])); // 输出一个包含大小写字母、数字以及字符 "!" 和 "@" 的长度为 12 的随机字符串
  */

 randomStringfunction (length, exclude = [], append = []{
  let characters = zhongjyuan.config.random.characters;
  let result = "";

  if (exclude.length > 0) {
   const excludeChars = exclude.join("");
   characters = characters.replace(new RegExp(`[${excludeChars}]`"g"), "");
  }

  if (append.length > 0) {
   characters += append.join("");
  }

  for (let i = 0; i < length; i++) {
   const index = Math.floor(Math.random() * characters.length);
   result += characters.charAt(index);
  }

  return result;
 },

randomColor:生成一个随机的 RGB 颜色字符串

alt
 /**
  * 生成一个随机的 RGB 颜色字符串
  * @returns {string} - 返回生成的随机 RGB 颜色字符串
  *
  * @example
  * console.log(randomColor()); // 输出一个随机的 RGB 颜色字符串,如 "rgb(135,88,201)"
  */

 randomColorfunction ({
  let red = zhongjyuan.helper.randomInt(0200);
  let green = zhongjyuan.helper.randomInt(0200);
  let blue = zhongjyuan.helper.randomInt(0200);
  return `rgb(${red},${green},${blue})`;
 },

本文由 mdnice 多平台发布

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值