JS生成任意范围随机数,JS生成任意长度随机字符串

生成随机数

/**
 * 生成任意范围内随机数
 * 支持正数,负数,整数,小数
 * 默认范围[0, 100]
 * min: 最小值
 * max: 最大值
 * len: 小数点后位数
 */
function randomNum(min = 0, max = 100, len = 0) {
  return Number((min + (max - min) * Math.random()).toFixed(len));
}

/**
 * 测试
 */
function randomNumTest() {
  setInterval(() => {
    console.log(randomNum(0, 100, 2));
  }, 100);
}

randomNumTest();

生成随机字符串

/**
 * 生成任意长度随机字符串
 * 包含数字、大写字母、小写字母
 * len: 字符串长度
 * 注意:用到了上面的随机数方法
 */
function randomStr(len = 8) {
  let str = '';
  let list = '0123456789abcdefghijklmnopqrstuvwxyz';
  for (let i = 0; i < len; i++) {
    let index = randomNum(0, 35);
    let word = list[index];
    if (isNaN(word) && randomNum() < 50) {
      word = word.toUpperCase();
    }
    str += word;
  }
  return str;
}

/**
 * 测试
 */
function randomStrTest() {
  setInterval(() => {
    console.log(randomStr(36));
  }, 100);
}

randomStrTest();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章