前言
在 ES6 中,Math 对象进行了大量的改进和优化,新增了一些常用的方法。这些方法帮助我们更高效地开发前端应用,并且可以在不依赖第三方工具库的情况下,操作数学运算。
本文将详细介绍 ES6 中新增的 Math 对象方法,并提供相关的示例代码,包含以下内容:
Math.clz32()
: 返回一个数的前导零位个数。Math.sign()
: 判断一个数是正数、负数还是零。Math.trunc()
: 取整数部分。Math.fround()
: 将一个数进行单精度浮点数运算并返回结果。Math.cbrt()
: 计算一个数的立方根。Math.imul()
: 返回两个数的32位整数乘积。Math.log10()
: 返回一个数的以 10 为底的对数。Math.log2()
: 返回一个数的以 2 为底的对数。Math.log1p()
: 返回一个数加 1 的自然对数。Math.expm1()
: 返回 e 的 x 次方 - 1。Math.sinh()
: 返回一个数的双曲正弦值。Math.cosh()
: 返回一个数的双曲余弦值。Math.tanh()
: 返回一个数的双曲正切值。Math.asinh()
: 返回一个数的反双曲正弦值。Math.acosh()
: 返回一个数的反双曲余弦值。Math.atanh()
: 返回一个数的反双曲正切值。
Math.clz32()
Math.clz32()
方法用于返回一个数的32位二进制数表示中,前导零位的个数。如果该数为负数,则返回0。
console.log(Math.clz32(0)); // 32 console.log(Math.clz32(1)); // 31 console.log(Math.clz32(1000)); // 22
Math.sign()
Math.sign()
方法用于判断一个数是正数、负数还是零,返回值为 1、-1 或 0。
console.log(Math.sign(5)); // 1 console.log(Math.sign(-5)); // -1 console.log(Math.sign(0)); // 0
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.fround()
Math.fround()
方法用于将一个数进行单精度浮点数运算并返回结果。
console.log(Math.fround(3.1415)); // 3.1414999961853027
Math.cbrt()
Math.cbrt()
方法用于计算一个数的立方根。
console.log(Math.cbrt(27)); // 3 console.log(Math.cbrt(-27)); // -3 console.log(Math.cbrt(64)); // 4
Math.imul()
Math.imul()
方法返回两个数的32位整数乘积。
console.log(Math.imul(2, 4)); // 8 console.log(Math.imul(-1, 8)); // -8
Math.log10()
Math.log10()
方法返回一个数的以 10 为底的对数。
console.log(Math.log10(100)); // 2 console.log(Math.log10(1000)); // 3
Math.log2()
Math.log2()
方法返回一个数的以 2 为底的对数。
console.log(Math.log2(2)); // 1 console.log(Math.log2(8)); // 3
Math.log1p()
Math.log1p()
方法返回一个数加 1 的自然对数。
console.log(Math.log1p(1)); // 0.6931471805599453 console.log(Math.log1p(Math.E - 1)); // 1
Math.expm1()
Math.expm1()
方法返回 e 的 x 次方 - 1。
console.log(Math.expm1(1)); // 1.718281828459045 console.log(Math.expm1(0)); // 0
Math.sinh()
Math.sinh()
方法返回一个数的双曲正弦值。
console.log(Math.sinh(0)); // 0 console.log(Math.sinh(1)); // 1.1752011936438014
Math.cosh()
Math.cosh()
方法返回一个数的双曲余弦值。
console.log(Math.cosh(0)); // 1 console.log(Math.cosh(1)); // 1.5430806348152437
Math.tanh()
Math.tanh()
方法返回一个数的双曲正切值。
console.log(Math.tanh(-2)); // -0.9640275800758169 console.log(Math.tanh(0)); // 0
Math.asinh()
Math.asinh()
方法返回一个数的反双曲正弦值。
console.log(Math.asinh(2)); // 1.4436354751788103 console.log(Math.asinh(0)); // 0
Math.acosh()
Math.acosh()
方法返回一个数的反双曲余弦值。
console.log(Math.acosh(1)); // 0 console.log(Math.acosh(2)); // 1.3169578969248166
Math.atanh()
Math.atanh()
方法返回一个数的反双曲正切值。
console.log(Math.atanh(-0.5)); // -0.5493061443340549 console.log(Math.atanh(0)); // 0
结语
在本文中,我们详细介绍了 ES6 中新增的 Math 对象方法,并提供了相关的示例代码。这些方法让我们更加高效、便捷地进行数学计算,提高了开发效率。
通过仔细学习这些方法,并在开发中灵活应用,我们可以进一步提升自己的语言,更好地完成前端开发的工作。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c92ef9e46428fe9e043bc9