Math对象的使用总结-JavaScript

89 阅读2分钟

ECMAScript 提供了 Math 对象作为保存数学公式、信息和计算的地方。Math 对象提供了一些辅助计算的属性和方法。

一、特殊值

属性说明
Math.E自然对数的基数 e 的值
Math.LN1010 为底的自然对数
Math.LN22 为底的自然对数
Math.LOG2E以 2 为底 e 的对数
Math.LOG10E以 10 为底 e 的对数
Math.PIπ 的值
Math.SQRT1_21/2 的平方根
Math.SQRT22 的平方根

二、min()和 max()方法

min()和 max()方法用于确定一组数值中的最小值和最大值。

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 max2= Math.max(...val);
console.log(max2); // 8

三、舍入方法

接下来是用于把小数值舍入为整数的 4 个方法:Math.ceil()、Math.floor()、Math.round() 和 Math.fround()。这几个方法处理舍入的方式如下所述。

1.Math.ceil()方法始终向上舍入为最接近的整数。

2.Math.floor()方法始终向下舍入为最接近的整数。

3.Math.round()方法执行四舍五入。

4.Math.fround()方法返回数值最接近的单精度(32 位)浮点值表示。

console.log(Math.ceil(25.9)); // 26 
console.log(Math.ceil(25.5)); // 26 
console.log(Math.ceil(25.1)); // 26 
console.log(Math.round(25.9)); // 26 
console.log(Math.round(25.5)); // 26 
console.log(Math.round(25.1)); // 25 
console.log(Math.fround(0.4)); // 0.4000000059604645 
console.log(Math.fround(0.5)); // 0.5 
console.log(Math.fround(25.9)); // 25.899999618530273 
console.log(Math.floor(25.9)); // 25 
console.log(Math.floor(25.5)); // 25 
console.log(Math.floor(25.1)); // 25

四、 random()方法

Math.random()方法返回一个 0~1 范围内的随机数,其中包含 0 但不包含 1。

//想从 1~10 范围内随机选择一个数
let num = Math.floor(Math.random() * 10 + 1);
//个 2~10 范围内的值
let num2 = Math.floor(Math.random() * 9 + 2);

Math.random()方法在这里出于演示目的是没有问题的。如果是为了加密而需要 生成随机数(传给生成器的输入需要较高的不确定性),那么建议使用 window.crypto. getRandomValues()。

五、其他方法

方法说明
Math.abs(x)返回 x 的绝对值
Math.exp(x)返回 Math.E 的 x 次幂
Math.expm1(x)等于 Math.exp(x) - 1
Math.log(x)返回 x 的自然对数
Math.log1p(x)等于 1 + Math.log(x)
Math.pow(x, power)返回 x 的 power 次幂
Math.hypot(...nums)返回 nums 中每个数平方和的平方根
Math.clz32(x)返回 32 位整数 x 的前置零的数量
Math.sign(x)返回表示 x 符号的 1、0、-0 或-1
Math.trunc(x)返回 x 的整数部分,删除所有小数
Math.sqrt(x)返回 x 的平方根
Math.cbrt(x)返回 x 的立方根
Math.acos(x)返回 x 的反余弦
Math.acosh(x)返回 x 的反双曲余弦
Math.asin(x)返回 x 的反正弦
Math.asinh(x)返回 x 的反双曲正弦
Math.atan(x)返回 x 的反正切
Math.atanh(x)返回 x 的反双曲正切
Math.atan2(y, x)返回 y/x 的反正切
Math.cos(x)返回 x 的余弦
Math.sin(x)返回 x 的正弦
Math.tan(x)返回 x 的正切

对正弦、余弦、正切等计算的实现取决于浏览器,因为计算这些值的方式有很多种。结果,这些方法的精度可能因实现而异。