JavaScript Match

JavaScript Match


 随机数

// 随机数  Math.random() 随机生成一个大于等于0且小于1的小数。
// 0>= r < 1 [0,1)  0~0.99999·····
console.log(Math.random());
console.log(Math.random());
console.log(Math.random());
console.log(Math.random());

// 计算概率
console.log(Math.random()<0.5?"❀":"字");

//谁去拿买卖
var r=Math.random();
console.log(
    r<0.33?"张":
        r<0.66?"王":
            "乔"
);

  

// 取[0,10)之间一个数。
console.log(Math.random()*10);
// 取[0,5)之间一个数。
console.log(Math.random()*5);


// 取[0,10)之间一个整数。
console.log(
    // Math.random()*max
    Math.floor(Math.random()*10)
);// math.floor() 取整

// 取[0,5)之间一个整数。
console.log(parseInt(Math.random()*5)); // math.floor() 取整


// 取[1,10] 之间一个整数。
console.log(Math.floor(Math.random()*10)+1); // math.floor() 取整
// 取[1,5]之间一个整数。
console.log(parseInt(Math.random()*5)+1); // math.floor() 取整


// 取 [22,35] 之间的随机整数
console.log(
    // Math.floor(Math.random()*(max-min+1))+min
    Math.floor(Math.random()*14)+22
);

    

案例:

  随机生成一个四个字符的验证码,可包含大小写字母和数字

  大写字母的 Unicode 为65-90,小写字母的 Unicode 为 97-122.

    var arr=[];
    //将所有可用字符保存到数组中
    for(var i=0;i<10;i++){//0-9
      arr.push(i);
    }
    for(var i=65;i<=90;i++){//A-Z
      arr.push(String.fromCharCode(i));
    }
    for(var i=97;i<=122;i++){//a-z
      arr.push(String.fromCharCode(i));
    }

    //生成验证码
    var text="";
    for(var i=0;i<4;i++){
      text+=arr[parseInt(Math.random()*arr.length)];//0-arr.length-1
    }
    console.log(text);

    

发布了118 篇原创文章 · 获赞 123 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_42776111/article/details/104597382