Math对象
ECMA提供了Math对象作为保存数学公式、信息、计算的地方。Math对象提供了一些计算的属性和方法。
注意:Math对象上提供的计算要比直接使用js实现快得多,这是因为Math对象上的计算使用了JS引擎中更高效的实现和处理器指令。
1. Math对象 属性
2. max() 和 min()方法
let max = Math.max(3, 54, 32, 16);
console.log(max); // 54
let min = Math.min(3, 54, 32, 16);
console.log(min); // 3
// 使用扩展操作符
let values = [1, 2, 3, 4, 5, 6, 7, 8];
let max = Math.max(...val);
3. 舍入方法
- 把小数值舍入为整数,4个方法:Math.ceil()、Math.floor()、Math.round()、Math.fround()
Math.ceil()
:向上舍入
Math.floor()
:向下舍入
Math.round()
:四舍五入
Math.fround()
:返回数值最接近的单精度(32位)浮点值表示
4. random()方法
Math.random()
始终返回小数
公式: number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)
eg:
1、打印1~10的整数:
console.log(Math.floor(Math.random()*10 + 1))
/*
这个例子中,1~10总共10个数,所以可选总数 total_number_of_choices为 10,最小可能值 first_possible_value为 1
*/
2、通过函数算出可选总数和最小可能值
function func(lowerValue, upperValue) {
let choice = upperValue - lowerValue + 1; //最大值减最小值加1为可选总数
return Math.floor(Math.random()*choice + lowerValue);
}
func(2, 9); //输出2-9的随机数
5.其它常见方法
x的power次幂:Math.pow(x, power) eg:Math.pow(2, 4)=16
平方根: Math.sqrt(x)
立方根:Math.cbrt(x)