我在示例中看到,~~
和 Math.floor
的功能是相同的。它们都将一个数字向下舍入(我的理解是正确的吗?)
此外,根据这个测试,~~
比 Math.floor
更快:jsperf.com/math-round-vs
所以我想知道,~~
和 Math.floor
之间有什么区别吗?
我在示例中看到,~~
和 Math.floor
的功能是相同的。它们都将一个数字向下舍入(我的理解是正确的吗?)
此外,根据这个测试,~~
比 Math.floor
更快:jsperf.com/math-round-vs
所以我想知道,~~
和 Math.floor
之间有什么区别吗?
是的,位运算符通常不适用于负数。例如:
~~-6.8 == -6 // doesn’t round down, simply removes the decimals
Math.floor(-6.8) == -7
您也会得到0
而不是NaN
,例如:
~~'a' == 0
Math.floor('a') == NaN
~~n - (n < 0)
,但这只是残忍的做法。 - BlenderMath.floor(1559125440000.6) // 1559125440000
~~1559125440000.6 // 52311552