JS 中 Math 内置对象知识总结
5.4.2 Math
Math 对象作为保存数学公式、信息和计算的地方。提供了一些辅助计算的属性和方法。
注意: Math 对象提供的计算比直接在 JavaScript 实现的快得多, 因为 Math 对象使用了 JavaScript 引擎中更高效的实现和处理器指令。但使用 Math 计算的问题是精度会因浏览器、操作系统、指令集和硬件而异。
01. Math 对象属性
Math 对象的属性用于保存数学中的一些特殊值。
属性 | 说明 |
---|---|
Math.E | 自然对数的基数 e 的值 |
Math.LN10 | 10 为底的自然对数 |
Math.LN2 | 2 为底的自然对数 |
Math.LOG2E | 以 2 为底 e 的对数 |
Math.LOG10E | 以 10 为底 e 的对数 |
Math.PI | π的值 |
Math.SQRT1_2 | 1/2的平方根 |
Math.SQRT2 | 2的平方根 |
Math.PI 常用来求圆的面积,其他都不太常用。
02. min() 和 max() 方法
min() 和 max() 方法用于确定一组数值中的最小值和最大值。这两个方法都接收任意多个参数:
let max = Math.max(Math.PI,0,2,1,89);
console.log(max); // 89
let min = Math.min(3,5,4,12,Math.PI,0,-1);
console.log(min); // -1
要知道数组中的最大或最小值,只需要使用数组的扩展操作符即可:
let values = [1,2,3,4,5,6,7,8,9];
console.log(Math.max(...values)); // 9
console.log(Math.min(...values)); // 1
03. 舍入方法
接下来是用于把小数值舍入为整数的4个方法:
-
Math.ceil():始终向上舍入为最接近的整数。
-
Math.floor():始终向下舍入为最接近的整数。
-
Math.round():执行四舍五入。
-
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.floor(25.9)); // 25
console.log(Math.floor(25.5)); // 25
console.log(Math.floor(25.1)); // 25
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
04. random() 方法
Math.random() 方法返回一个 0~1 范围内的随机数,其中包含 0 但不包含 1。
从一组整数中随机选择一个数:first 表示从什么数开始,total 表示总共有多少个数。
let number = Math.floor(Math,random()*total + first);
如从1~10范围内随机选择一个数:
let number = Math.floor(Math.random()*10 + 1);
如从2~10范围内随机选择一个数:
let number = Math.floor(Math.random()*9 + 2);
可以下一个函数,获取 start 到 end 范围内的数:
function randomNumber(start,end){
let total = end - start + 1;
return Math.floor(Math.random()*total + start);
}
let num = randomNumber(1,2);
console.log(num);
使用这个函数,从一个数组中随机选择一个元素就很容易,比如:
let colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
let color = colors[randomNumber(0,colors.length-1)];
console.log(color);
05. 其他方法
Math 对象还有很多涉及各种简单或高阶数运算的方法。
方法 | 说明 |
---|---|
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 的正切 |