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