JavaScirpt Math.random 随机数

栗子:

// 0-9 (最小0,最大0.9999999999999999)

console.log(Math.random());

// 0-9(整数)

console.log(Math.floor(Math.random() * 10));

// 1-10(整数)

console.log(Math.floor(Math.random() * 10) + 1);

实践1:(随机点名)

 let arr = ["lyh", "szs", "lcx", "ssg", "ssq", "ssl", "ssm", "ssh"];

function getRandom(min, max) {

return min + Math.floor(Math.random() * (max - min + 1)); //含最大值,含最小值

}

console.log(arr[getRandom(0, arr.length - 1)])

实践2:(随机颜色)

function getRandomColor() {

var r = Math.floor(Math.random() * (255 + 1));

var g = Math.floor(Math.random() * (255 + 1));

var b = Math.floor(Math.random() * (255 + 1));

var rgb = "rgb(" + r + "," + g + "," + b + ")";

return rgb;

}

console.log(getRandomColor());

实践3:(随机验证码)

let str1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

let arrStr = str1.split("");

let res = "";

for (var i = 0; i < 4; i++) {

n = Math.floor(Math.random() * arrStr.length);

res += arrStr[n];

}

console.log(res);

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值