今天这篇给大家介绍一下Javascript中的一个内置对象-Math
数学对象,很简单,直接使用即可,不用设置,没有逻辑,记住就可以了
方法或属性:
属性:Math.PI圆周率
console.log(Math.PI);//3.141592653589793
var r = 100;
console.log(Math.PI * r * r) ;//31415.926535897932
console.log(2*2*Math.PI.toFixed(3))//12.568结果保留了三位小数
方法:
Math.round方法用于四舍五入
console.log(Math.round(45.678))// 46
console.log(Math.round(45.378))//45
console.log(Math.round(-45.678))//-46
随机数:0~1,不包括0和1
console.log(Math.random());
Math.abs方法返回参数值的绝对值。
Math.abs(1) // 1
Math.abs(-1) // 1
Math.max方法返回参数之中最大的那个值,Math.min返回最小的那个值。如果参数为空, Math.min返回Infinity, Math.max返回-Infinity。
Infinity 用于存放表示正无穷大的数值
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
Math.min() // Infinity
Math.max() // -Infinity
Math.floor方法小于参数值的最大整数(地板值)。
Math.floor(3.2) // 3
Math.floor(-3.2) // -4
Math.ceil方法返回大于参数值的最小整数(天花板值)
Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3
Math.pow方法返回以第一个参数为底数、第二个参数为幂的指数值。
// 等同于 2 ** 2
Math.pow(2, 2) // 4
// 等同于 2 ** 3
Math.pow(2, 3) // 8
Math.sqrt方法返回参数值的平方根。如果参数是一个负值,则返回NaN。
Math.sqrt(4) // 2
Math.sqrt(-4) // NaN
max和min接收的是多个参数,不是一个数组,也不能接收一个数组,强行写,会得到NaN
console.log(Math.max(34,56,37,24,89,13)); // 89
console.log(Math.min(34,56,37,24,89,13)); // 13
console.log(Math.min([34,56,37,24,89,13])); // NaN
sin和cos方法接收的是弧度,不是角度
90的角度
console.log(Math.sin( Math.PI / 180 * 90 ));//1
console.log(Math.cos( Math.PI / 180 * 90 ));//6.123233995736766e-17
计算斜边
console.log(Math.sqrt(3*3+4*4))//5
注释:Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math(),像 Math.sin() 这样的函数只是函数,不是某个对象的方法。您无需创建它,通过把 Math 作为对象使用就可以调用其所有属性和方法。
新人初来,有很多欠缺需要大家多多指教,逆疫而战大家加油