Javascript 整数除法,或者 Math.floor(x) 等于 x | 0 表示 x >= 0?

Mis*_*hko 1 javascript division integer-division

看下面的例子,它看起来Math.floor(x)相当于x | 0, for 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
Run Code Online (Sandbox Code Playgroud)

这对于在 Javascript 中执行整数除法非常有用:(5 / 3) | 0而不是Math.floor(5 / 3).

Mat*_*ens 5

位运算符将数字转换为 32 位序列。因此,您\xe2\x80\x99re 建议的替代方案仅适用于正符号 32 位浮点数,即从0+2,147,483,647(2^31-1 ) 的数字。

\n\n
Math.floor(2147483646.4); // 2147483647\n2147483646.4 | 0; // 2147483647\n// but\xe2\x80\xa6\nMath.floor(2147483648.4); // 2147483648\n2147483648.4 | 0; // -2147483648\n
Run Code Online (Sandbox Code Playgroud)\n\n

另一个区别:如果x不是数字,则结果x | 0可能与Math.floor(x)

\n\n
Math.floor(NaN); // NaN\nNaN | 0; // 0\n
Run Code Online (Sandbox Code Playgroud)\n\n

除此之外,结果应该类似于Math.floor()只要使用正数,结果应该与 的结果类似。

\n\n

以下是更多示例+性能测试:http://jsperf.com/rounding-numbers-down

\n