文章目录
在ES6中,Math对象上新增了17个与数学相关的方法,这些方法只能在Math对象上调用。
Math对象的扩展
Math.trunc()
基本用法
Math.trunc()
方法用于去除一个数的小数部分,返回整数部分。
console.log(Math.trunc(4.1)); // 4
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.1)); // -4
- 对于非数值的类型,
Math.trunc()
内部会先使用Number()
方法转换成数值,然后在做运算。 - 对于空值和无法截取的整数的值,返回
NaN
.
在没有此方法的情况下模拟使用
Math.trunc = Math.trunc || function(x){
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
Math.sign()
Math.sign()
方法用来判断一个数是正数?负数还是零。
对于非数值,会将其转换为数值
Math.sign()
的返回值
- 参数为正数,返回
+1
- 参数为负数,返回
-1
- 参数为0,返回
0
- 参数为-0,返回
-0
- 其他值,返回
NaN
在没有此方法的情况下模拟使用
Math.sign = Math.sign || function(x) {
x = +x;
if( x === 0 || isNaN(x)){
return x;
}
return x > 0 ? 1 : -1;
}
Math.cbrt()
-
Math.cbrt()
用来计算参数的立方根 -
对于非数值,
Math.cbrt()
方法内部是先使用Number()
方法将其转换成数值,然后做运算。
在没有此方法的情况下模拟使用
Math.cbrt = Math.cbrt || function(x) {
var y = Math.pow(Math.abs(x), 1/3);
return x < 0 ? -y : y;
}
Math.hypot()
Math.hypot()
返回所有参数的平方和的平方根
假设有两个参数:x
、y
,那么Math.hypot()
等同于
x
2
+
y
2
\sqrt{x^2 + y^2}
x2+y2的预算结果
- 如果参数不是数值,
Math.hypot()
方法会将其转换为数值,只要有一个参数无法转换,那么就会返回NaN
.
四个对数相关的方法
Math.expm1()
方法Math.expm1()
返回的值等同于数学公式:
e
x
−
1
e^x-1
ex−1的预算结果。
Math.log1p()
方法Math.log1p()
返回1+x
的自然对数,等同于:Math.log(1+x)
,如果x
小于-1,返回NaN
.
Math.log10()
方法Math.log10()
返回以10为底的x
的对数。如果x
小于0,则返回NaN
.
Math.log2()
方法Math.log2()
返回以2为底的x
的对数。如果x
小于0,则返回NaN
.
双曲函数
Math.sinh(x)
返回x
的双曲正弦Math.cosh(x)
返回x
的双曲余弦Math.tanh(x)
返回x
的双曲正切Math.asinh(x)
返回x
的反双曲正弦Math.acosh(x)
返回x
的反双曲余弦Math.atanh(x)
返回x
的反双曲x正切
Math对象已有的方法
Math.abs()
方法:Math.abs()
返回参数的绝对值
console.log(Math.abs(-3)); // 3
Math.ceil()
方法:Math.ceil()
是对参数的向上取整计算
console.log(Math.ceil(3.4)); // 4
Math.exp()
方法:Math.exp()
是e
的x
次幂的值;e 代表自然对数的底数,其值近似为 2.71828。
console.log(Math.exp(1)); // 2.718281828459045
Math.floor()
方法:Math.floor()
是对参数的向下取整计算
console.log(Math.floor(3.4)); // 3
Math.log()
方法:Math.log()
返回以自然对数(底为e)
console.log(Math.log(2.7183)); // 1.0000066849139877
Math.pow(x,y)
方法:Math.pow(x,y)
返回参数x的y次幂的值
console.log(Math.pow(2,2)); // 4
注意:如果结果是虚数或者负数,则返回NaN
,如果因为指数过大而引起溢出,则返回Infinity
Math.random()
方法:Math.random()
返回一个0~1
之间的随机数。
Math.round()
方法:Math.round()
返回参数四舍五入的运算结果
console.log(Math.round(3.1)); // 3
console.log(Math.round(3.9)); // 4
console.log(Math.round(-3.9)); // -4
console.log(Math.round(-0)); // -0
Math.sqrt()
方法:Math.sqrt()
返回参数平方根的运算结果
console.log(Math.sqrt(4)); // 2
console.log(Math.sqrt(-4)); // NaN
console.log(Math.sqrt(-0)); // -0
console.log(Math.sqrt(0)); // 0
备注:本文是自己学习阮一峰老师的《ECMAScript 6 入门》所做的笔记,大部分例子来源于此书。