获取极值的方法
1. 获取极值的方法
Math.min()函数的作用是找出一组参数中的最小数值。相反,Math.max()则用于寻找这组数值里的最大项。
alert(Math.min(2,4,3,6,3,8,0,1,3)); //最小值
alert(Math.max(4,7,8,3,1,9,6,0,3,2)); //最大值
数值舍入处理
2. 数值舍入处理
Math.ceil()负责执行向上舍入操作,其逻辑是将目标数值始终进位至最接近的整数;
Math.floor()执行向下舍入,即把数值始终退位取整至最接近的整数;
Math.round()执行标准的四舍五入,将数值舍入到距离最近的那个整数;
具体示例如下:
alert(Math.ceil(25.9)); //26
alert(Math.ceil(25.5)); //26
alert(Math.ceil(25.1)); //26
alert(Math.floor(25.9)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.1)); //25
alert(Math.round(25.9)); //26
alert(Math.round(25.5)); //26
alert(Math.round(25.1)); //25
生成随机数方法
3. 生成随机数方法
Math.random()能够返回一个介于0(含)到1(不含)之间的伪随机浮点数。若需扩大随机数的取值范围,可套用以下计算逻辑:
目标值 = Math.floor(Math.random() * 总数 + 起始值)
例如:
alert(Math.floor(Math.random() * 10 + 1)); //随机产生1-10之间的任意数
for (var i = 0; i<10;i ++) {
document.write(Math.floor(Math.random() * 10 + 5)); //5-14之间的任意数
document.write('
');
}
为了更便捷地传递所需的数值区间,可以将其封装为独立函数:
function selectFrom(lower, upper) {
var sum = upper - lower + 1; //总数-第一个数+1
return Math.floor(Math.random() * sum + lower);
}
for (var i=0 ;i<10;i++) {
document.write(selectFrom(5,10)); //直接传递范围即可
document.write('
');
}
其他常用方法
4. 其他常用方法
相关功能汇总于下表:
本文总结了上述内容,旨在帮助读者掌握这些工具,期待对您的开发工作有所助益,欢迎支持本站!
|
方 法 |
说 明 |
|
Math.abs(num) |
返回num的绝对值 |
|
Math.exp(num) |
返回Math.E的num次幂 |
|
Math.log(num) |
返回num的自然对数 |
|
Math.pow(num,power) |
返回num的power次幂 |
|
Math.sqrt(num) |
返回num的平方根 |
|
Math.acos(x) |
返回x的反余弦值 |
|
Math.asin(x) |
返回x的反正弦值 |
|
Math.atan(x) |
返回x的反正切值 |
|
Math.atan2(y,x) |
返回y/x的反正切值 |
|
Math.cos(x) |
返回x的余弦值 |
|
Math.sin(x) |
返回x的正弦值 |
|
Math.tan(x) |
返回x的正切值 |