Math.random()
var random = Math.random();
console.log(random);
Math.random()*(m-n)+n
var random1 = Math.random()*(15-10)+10;
var random2 = Math.random()*(15-10)+10;
var random3 = Math.random()*(15-10)+10;
console.log(random1);
console.log(random2);
console.log(random3);
因为 random 的特点,要取得这几个区间内的浮点数稍微麻烦些,需要借助一些判断才能满足要求。
//取得[n,m]范围随机数
function fullClose(n,m) {
var result = Math.random()*(m+1-n)+n;
while(result>m) {
result = Math.random()*(m+1-n)+n;
}
return result;
}
//取得(n,m)范围随机数
function fullOpen(n,m) {
var result = Math.random()*(m-n)+n;
while(result == n) {
result = Math.random()*(m-n)+n;
}
return result;
}
//取得(n,m]范围随机数
function leftOpen(n,m) {
var result = Math.random()*(m-n+1)+n-1;
while(result<n) {
result = Math.random()*(m-n+1)+n-1;
}
return result;
}
要生成随机整数,我们还需要借助如下两个方法: Math.round(num):将 num 四舍五入取整 Math.floor(num):将 num 向下取整,即返回 num 的整数部分。当然我们也可以使用 parseInt() 方法代替。
Math.round(Math.random())
var random1 = Math.round(Math.random());
var random2 = Math.round(Math.random());
var random3 = Math.round(Math.random());
console.log(random1);
console.log(random2);
console.log(random3);
Math.floor(Math.random()*n)
var random1 = Math.floor(Math.random()*5);
var random2 = Math.floor(Math.random()*5);
var random3 = Math.floor(Math.random()*5);
console.log(random1);
console.log(random2);
console.log(random3);
Math.floor(Math.random()*n)+1
var random1 = Math.floor(Math.random()*5)+1;
var random2 = Math.floor(Math.random()*5)+1;
var random3 = Math.floor(Math.random()*5)+1;
console.log(random1);
console.log(random2);
console.log(random3);
Math.floor(Math.random()*(max-min+1))+min
var random1 = Math.floor(Math.random()*(10-5+1))+5;
var random2 = Math.floor(Math.random()*(10-5+1))+5;
var random3 = Math.floor(Math.random()*(10-5+1))+5;
console.log(random1);
console.log(random2);
console.log(random3);
//生成n位数字字符串
function randomNum(n){
var res = "";
for(var i=0;i<n;i++){
res += Math.floor(Math.random()*10);
}
return res;
}
//测试
console.log(randomNum(3))
console.log(randomNum(5))
console.log(randomNum(7))
//生成n位数字字母混合字符串
function generateMixed(n) {
var chars = ['0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
var res = "";
for(var i = 0; i < n ; i++) {
var id = Math.floor(Math.random()*36);
res += chars[id];
}
return res;
}
//测试
console.log(generateMixed(3))
console.log(generateMixed(5))
console.log(generateMixed(7))