JavaScript的Math对象

1.?写一个函数,返回从min到max之间的随机整数,包括min不包括max
?
function randomNumber(min,max){
return Math.floor(Math.random() * (max-min) + min);
}
randomNumber(10,15);

?2.?写一个函数,返回从min都max之间的 随机整数,包括min包括max
?
function randomNumber(min,max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNumber(2,8);

3.?写一个函数,生成一个长度为 n 的随机字符串,字符串字符的取值范围包括0到9,a到 z,A到Z。
?
function getRandStr(num){
var str = '0123456789qwertyuiopasdfghjklzxcvbnmPOIUYTREWQASDFGHJKLMNBVCXZ';
var newStr = '';
for(var i = 0; i < parseInt(num); i++){
newStr += str[ Math.floor(Math.random() * str.length) ];
}
return newStr;
}
getRandStr(10);

4.?写一个函数,生成一个随机 IP 地址,一个合法的 IP 地址为 0.0.0.0~255.255.255.255
?
function getRandIP(){
var newIp = "";
for(var i =0; i < 4; i++){
newIp += Math.floor(Math.random() * 255) + 1 +',';
}
return newIp.substring(0, newIp.length-1);
}
getRandIP();

5.?写一个函数,生成一个随机颜色字符串,合法的颜色为#000000~ #ffffff
?
function getRandColor(){
var str = '1234567890abcdef';
var colorStr = '#';
for(var i =0; i < 6; i++){
colorStr += str[ Math.floor(Math.random() * str.length) ];
}
return colorStr;
}
var color = getRandColor();
document.body.style.backgroundColor = color;


?

0 个评论

要回复文章请先登录注册