ES6中Math对象新增的方法实例详解
ES6中的Math对象新增了一些方法,这些方法主要用于数值运算和数字转换。下面我们来逐一介绍这些方法。
1. Math.trunc()
Math.trunc()方法可以去除一个数的小数部分,返回整数部分,相当于将一个浮点数向0取整。比如:
Math.trunc(4.9); // 4
Math.trunc(-4.9); // -4
Math.trunc(3); // 3
Math.trunc(-3); // -3
2. Math.sign()
Math.sign()方法用于判断一个数的正负性。如果参数是正数,返回+1;如果是负数,返回-1;如果是0,返回0;如果是其他值,返回NaN。比如:
Math.sign(3); // 1
Math.sign(-3); // -1
Math.sign(0); // 0
Math.sign('hello'); // NaN
3. Math.cbrt()
Math.cbrt()方法用于计算一个数的立方根。比如:
Math.cbrt(27); // 3
Math.cbrt(64); // 4
4. Math.log10()
Math.log10()方法用于计算一个数的以10为底的对数。比如:
Math.log10(100); // 2
Math.log10(1000); // 3
5. Math.log2()
Math.log2()方法用于计算一个数的以2为底的对数。比如:
Math.log2(8); // 3
Math.log2(16); // 4
6. Math.hypot()
Math.hypot()方法用于计算所有参数的平方和的开方,可以用于计算勾股定理。比如:
Math.hypot(3, 4); // 5
Math.hypot(5, 12); // 13
7. Math.sinh()
Math.sinh()方法用于计算一个数的双曲正弦值。比如:
Math.sinh(0); // 0
Math.sinh(1); // 1.1752011936438014
8. Math.cosh()
Math.cosh()方法用于计算一个数的双曲余弦值。比如:
Math.cosh(0); // 1
Math.cosh(1); // 1.5430806348152437
9. Math.tanh()
Math.tanh()方法用于计算一个数的双曲正切值。比如:
Math.tanh(0); // 0
Math.tanh(-1); // -0.7615941559557649
10. Math.asinh()
Math.asinh()方法用于计算一个数的反双曲正弦值。比如:
Math.asinh(0); // 0
Math.asinh(1); // 0.8813735870195429
11. Math.acosh()
Math.acosh()方法用于计算一个数的反双曲余弦值。比如:
Math.acosh(1); // 0
Math.acosh(2); // 1.3169578969248166
12. Math.atanh()
Math.atanh()方法用于计算一个数的反双曲正切值。比如:
Math.atanh(0); // 0
Math.atanh(0.5); // 0.5493061443340549
总结:
ES6中Math对象新增的方法主要用于数值运算和数字转换,包括去除小数部分、判断正负性、计算对数、计算立方根、勾股定理等等。这些方法可以方便地进行数值计算和转换,适用于各种的科学计算和数据处理应用。
