看下面的例子,看起来 Math.floor(x)
等同于 x | 0
,对于 x >= 0
。真的是这样吗?如果是,为什么? (或者 x | 0
是如何计算的?)
x = -2.9; console.log(Math.floor(x) + ", " + (x | 0)); // -3, -2
x = -2.3; console.log(Math.floor(x) + ", " + (x | 0)); // -3, -2
x = -2; console.log(Math.floor(x) + ", " + (x | 0)); // -2, -2
x = -0.5; console.log(Math.floor(x) + ", " + (x | 0)); // -1, 0
x = 0; console.log(Math.floor(x) + ", " + (x | 0)); // 0, 0
x = 0.5; console.log(Math.floor(x) + ", " + (x | 0)); // 0, 0
x = 2; console.log(Math.floor(x) + ", " + (x | 0)); // 2, 2
x = 2.3; console.log(Math.floor(x) + ", " + (x | 0)); // 2, 2
x = 2.9; console.log(Math.floor(x) + ", " + (x | 0)); // 2, 2
x = 3.1; console.log(Math.floor(x) + ", " + (x | 0)); // 3, 3
这对于在 Javascript 中执行整数除法很有用:(5/3) | 0
而不是 Math.floor(5/3)
。
最佳答案
按位运算符将数字转换为 32 位序列。因此,您建议的替代方案仅适用于带正符号的 32 位 float ,即从 0
到 +2,147,483,647
的数字(2^31-1
).
Math.floor(2147483646.4); // 2147483647
2147483646.4 | 0; // 2147483647
// but…
Math.floor(2147483648.4); // 2147483648
2147483648.4 | 0; // -2147483648
另一个区别:如果x
不是数字,x |的结果0
可能与 Math.floor(x)
的不同。
Math.floor(NaN); // NaN
NaN | 0; // 0
除此之外,结果应该类似于Math.floor()
,只要使用正数即可。
这里有一些例子+性能测试:http://jsperf.com/rounding-numbers-down
关于Javascript Integer Division,或者 Math.floor(x) 等同于 x | 0 表示 x >= 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9391718/