js隨機生成數字隨機生成字母;js隨機生成大寫字母;js隨機生成0-9的數字;隨機生成幾位數字;js隨機數相關;


隨機數或隨機字母常用的方法:

 

Math.random()隨機生成 [0-1)之間的數。數字的范圍為包含0,小於1

String.fromCharCode:(num):將ascii碼轉換成對應的字符

字符變量.charCodeAt()獲取字符的ascii碼

 

 

 

Math.ceil(num): 將數向上取整。--- Math.ceil(0.1)=1; Math.ceil(0.9)=1

Math.floor(num):將數向下取整--- Math.floor(0.1)=0; Math.floor(0.9)=0

Math.round(num):將數四舍五入取整。--- Math.round(1.4)=1; Math.round(1.5)=2

Math.max:求所有參數中的最大值。--- Math.max(1, 2, 56, 78, 99, 0, 46, 23)=99

Math.min:求所有參數中的最小值。--- Math.min(1, 2, 56, 78, 99, 0, 46, 23)=0

 
 
常見的Math函數的方法:

 

 

1、需求:隨機生成范圍為10-20的數 
//  分解邏輯
let num = Math.random() * 11  // num:0-10.9999999...
let num1 = Math.floor(num)  // num1:0-10
let num2 = 10 + num1  // num2:10-20

let Num = 10 + Math.floor(Math.random() * 11)

// 要生成范圍為24-45的數則為:
let Num1 = 24 + Math.floor(Math.random() * (45-24+1))
// 最小為24+0;最大為24+21 

 

 

2、需求:隨機生成n位數字,每個數的范圍是0-9

        // 隨機生成n位數字
        forNum(n) {
            let num = ''
            for (let i = 0; i < n; i++) {
                // Math.random():隨機生成 [0-1)之間的數
                // Math.floor():向下取整,0.9=0;9.9=9
                num += Math.floor(Math.random() * 10)
            }
            return num
        }

 分析:

  需要生成4位數字,如7563,則調用時 forNum(4)

  for循環4次,每次生成一位數字

  生成 [0,1)范圍內的數字,*10,則最大可能是9.9999999...

  隨后向下取整,則最后數的范圍為0-9的數

  每次循環都將數添加到變量的末尾,則循環結束后得到一個4位的數

 

3、需求:隨機生成26個字母內的其中一個大寫字母

let str = String.fromCharCode(65 + Math.floor(Math.random() * 26))

 分析:

  首先英文第一個大寫字母A的ascii碼為65,一共26個字母

  則大寫字母ascii碼范圍為65-90

  那么首先要生成范圍為65-90的一個整數

  Math.random() * 26:最小生成0,最大生成25.9999999999...

  Math.floor(0至25.9999999...):最小取整值為0,最大取整值為25

  隨后 +65,則范圍為65+0至65+25;就已經是26個大寫字母的ascii碼了

  調用 String.fromCharCode(ascii碼),將ascii碼轉換成對應的大寫字母


 4、需求:JS 隨機生成字母數字組合(包含大寫字母)

randomString(len, charSet) {
  charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let randomString = '';
  for (let i = 0; i < len; i++) {
    let randomPoz = Math.floor(Math.random() * charSet.length);
    randomString += charSet.substring(randomPoz,randomPoz+1);
  }
  console.log(randomString);
}

解釋:

調用:this.randomString(10,'~!@#$%^&*()0123456789')

  len為10:拼接后的字符串長度為10;charSet可取字符為:~!@#$%^&*()0123456789

調用:this.randomString(8)

  沒有傳入charSet可取字符

  則使用默認的可取字符:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

 


免責聲明!

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



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