In js, in the past, the Math.floor method was used to round down, but now we see this usage: OR operation
interval = interval | 0
Why can we round down in this way? , what are the advantages of this usage compared with Math.floor?
某草草2017-06-26 10:57:11
Note that |
is not a logical OR, but a bitwise OR (OR).
Some small differences. For example, Math.floor(NaN)
still returns NaN
. But NaN | 0
returns 0.
Another example is Math.floor(Infinity)
returns Infinity
, but Infinity | 0
returns 0
给我你的怀抱2017-06-26 10:57:11
First of all, S1ngS1ng upstairs is right about those small differences.
In addition, |
is a bitwise OR operation. Since when 0
is stored in the memory, all integer bits are filled with 0, so the OR operation is performed based on the binary bit and a numerical value. Regardless of the corresponding bit Whether 0
or 1
is ORed with 0
, you will get itself. However, since the number 0 does not have a decimal part in the memory, the decimal part of interval
is discarded after the bitwise OR operation. In fact, rounding down is achieved by discarding the decimal part.
Since it is a bit operation, it will be faster than Math.floor()
.
三叔2017-06-26 10:57:11
The real reason is: automatic type conversion within js.
js values are all expressed in 64-bit
floating point type. When a value requires bit operations
, js will automatically convert it into a 32-bit signed
integer and discard the decimal part.
n|0; n>>0; //The following 0 is only used to ensure that the integer value of n remains unchanged.
Reducing from 64-bit to 32-bit will cause a loss of accuracy. Be careful!
, maximum effective range: 2^32/2-1
> f64=(Math.pow( 2,32)/2-1)-0.5
2147483646.5
> f64|0
2147483646
> f64>>0
2147483646
> (f64 + 2)|0 //超出有效范围
-2147483648
> (f64 + 2)>>0 //超出有效范围
-2147483648
> Math.floor(f64 + 2) //正确
2147483648
给我你的怀抱2017-06-26 10:57:11
Both can be achieved, interval = interval | 0
This is a writing technique, it depends on personal preference. It may be that interval = interval | 0
will run faster, and writing code will definitely be faster than Math.floor
!