产生一个指定长度指定内容的随机字符串

书写一个函数,产生一个指定长度的随机字符串,字符串中只能包含大写字母、小写字母、数字

function getRandom(min,max){
    // Math.random() 0~1之间的小数
    // Math.random()*5 0~5之间的小数
    // Math.random()*5+(3) (0+3)~(5+3)之间的小数 3最小值  8最大值
    // Math.random()*10 0~10之间的小数
    // Math.random()*10+(5) (0+5)~(10+5)之间的小数 5最小值 15最大值
    // 从而得出  Math.random()*(max-min)+min
    // // Math.floor向下取整
    return Math.floor( Math.random()*(max-min)+min )
}
function randomStr(len){
        let contentScope = "";
        //将 Unicode 编码转为一个字符: String.fromCharCode();
        // 大写字母对应的 Unicode
        for(let i=65;i<65+26;i++){
            contentScope+=String.fromCharCode( getRandom(65,65+26) )
        }
        // 小写字母对应的 Unicode
        for(let i=97;i<97+26;i++){
            contentScope+=String.fromCharCode( getRandom(97,97+26) )
        }
        // 叔子对应的 Unicode
        for(let i=48;i<48+10;i++){
            contentScope+=String.fromCharCode( getRandom(48,48+10) )
        }
        let rmStr = "";
      for(let i=0;i<len;i++){
            let rm = getRandom(0,contentScope.length-1);
        rmStr+=contentScope[rm]
      }
      console.log(rmStr)
      return rmStr;
}
randomStr(10);



©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容