JavaScript中的Math数学对象
Math数学对象
Math对象是一个静态对象,换句话说:在使用Math对象,不需要创建实例。
Math.PI:圆周率。
Math.abs():绝对值。如:Math.abs(-9) = 9
Math.ceil():向上取整(整数加1,小数去掉)。如:Math.ceil(10.2) = 11
Math.floor():向下取整(直接去掉小数)。如:Math.floor(9.888) = 9
Math.round():四舍五入。如:Math.round(4.5) = 5; Math.round(4.1) = 4
Math.pow(x,y):求x的y次方。如:Math.pow(2,3) = 8
Math.sqrt():求平方根。如:Math.sqrt(121) = 11
Math.random():返回一个0到1之间的随机小数。如:Math.random() = 0.12204467732259783
注:求(min,max)之间的随机数。公式为:Math.random()*(max-min)+min
实例:0-10之间的随机整数;求10-20之间的随机整数;求20到30之间的随机整数;求7到91之间的随机整数
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>php.cn</title>
<script>
//求两个整数之间的随机整数
//定义随机数的函数
function getRandom(min,max){
//求随机数
var random =Math.random()*(max-min)+min;
//向下取整
random = Math.floor(random);
//输出结果
document.write(random+"<hr>");
}
//调用函数
getRandom(0,100);
getRandom(5,89);
getRandom(100,999);
</script>
</head>
<body>
</body>
</html>实例:随机网页背景色
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> </head> <body> </body> </html> <script> var min = 100000; var max = 999999; var random = Math.random() *(max-min)+min; //向下取整 random = Math.floor(random); document.body.bgColor = "#"+random; </script>

巅峰之前
求随机数的公式不用MAX-MIN吧,直接乘MAX+MIN应该就可以了吧。因为返回的是0-1之间的数字,不会是0,也不会是1。
6年前 添加回复 0