Math:数学对象
Math 对象不是构造函数,它具有数学常数和函数的属性和方法。跟数学相关的运算(求绝对值,取整、最大值等)可以使用 Math 中的成员。
- 创建:
特点:Math对象不用创建,直接使用。 Math.方法名(); - 方法:
Math.PI // 圆周率
Math.floor() // 向下取整
Math.ceil() // 向上取整
Math.round() // 四舍五入版 就近取整 注意 -3.5 结果是 -3
Math.abs() // 绝对值
Math.max()/Math.min() // 求最大和最小值
Math.random():返回0-1之间的随机数。含0不含1;
document.write(Math.PI+"<br>");//3.141592653589793
document.write(Math.random()+"<br>");
document.write(Math.round(3.14)+"<br>");//3
document.write(Math.ceil(3.14)+"<br>");//4
document.write(Math.floor(3.14)+"<br>");//3
/*
取1-100之间的随机整数
*/
document.write(Math.ceil(Math.random()*100);
随机数方法 random()
random() 方法可以随机返回一个小数,其取值范围是 [0,1),左闭右开 0 <= x < 1
得到一个两数之间的随机整数,包括两个数在内
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}