1. 程式人生 > >JS生成任意範圍隨機數,JS生成任意長度隨機字串

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();