查看以下示例,它看起来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
这对于在 Javascript 中执行整数除法很有用:(5 / 3) | 0
而不是Math.floor(5 / 3)
.