Logo
Section 1 / 2

数学扩展

ES6 中的内置数学函数

导入

数学扩展

ES6 中的内置数学函数

Number 和 Math 对象都新增了许多有用的方法。ES6 中引入了许多新的数学函数。

在我看来,最有用且语义清晰的新增功能是 Math.trunc,它可以获取一个数字的截断整数值。

1console.log(Math.trunc(1.99)); 2console.log(Math.trunc(-1.99));

另一个扩展是 Math.sign,它用于获取一个数字的符号。尽管 > 和 < 操作符仍然可以构成正确的布尔表达式,但在进行计算时,sign 函数有时仍然很有用。

1console.log(Math.sign(5)); 2//> 1 3 4console.log(Math.sign('5')); 5//> 1 6 7console.log(Math.sign(0)); 8//> 0 9 10console.log(Math.sign(-0)); 11//> -0 12 13console.log(Math.sign('')); 14//> 0 15 16console.log(Math.sign('twenty')); 17//> NaN 18 19console.log(Math.sign(NaN)); 20//> NaN

其他新增的 Math 函数包括:

函数用途
Math.cbrt立方根
Math.clz32计算 32 位整数的前导零个数
Math.exp(num)返回 e^num(e ≈ 2.718...)
Math.expm1(num)等价于 Math.exp(num) - 1
Math.fround四舍五入到最接近的 32 位浮点值
Math.sinh、Math.cosh、Math.tanh、Math.asinh、Math.acosh、Math.atanh双曲函数
Math.hypot返回各参数平方和的平方根
Math.imul32 位整数乘法
Math.log2以 2 为底的对数
Math.log10以 10 为底的对数
Math.log(num)num 的自然对数(ln)
Math.log1p(num)等价于 Math.log(num + 1)

代理的实际应用

数字扩展