JS中常見獲取隨機數的方法


JS 獲取固定區間的隨機數

const start = 0;
const end = 20;
// parseInt
parseInt(Math.random() * (end - start + 1)) + start;
// floor
Math.floor(Math.random() * (end - start + 1)) + start;
// ceil
Math.ceil(Math.random() * (end - start + 1));
// 注意 round 首尾不是等比例 首尾比例是其他的 1/2
Math.round(Math.random() * (max - min)) + min;

JS 簡單生成由字母數字組合隨機字符串示例

/*
 ** randomWord 產生任意長度隨機字母數字組合
 ** randomFlag-是否任意長度 min-任意長度最小位[固定位數] max-任意長度最大位 , true 使用min - max  false 使用 min
 ** xuanfeng 2014-08-28
 */
function randomWord(randomFlag, min, max) {
  var str = "",
    range = min,
    arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // 隨機產生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min;
  }
  for (var i = 0; i < range; i++) {
    pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM