栗子:
// 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);