生成指定位数的纯数字字符串
//生成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))
生成 [ min, max ] 范围内的随机整数(大于等于min,小于等于max)
(1)下面方法生成一个最小值为 min,最大值为 max 的随机整数。
Math.floor(Math.random()*(max-min+1))+min
(2)比如下面生成几个 5 到 10 的随机整数
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);