0" mean in JavaScript

This question already has an answer here:

  • Using bitwise OR 0 to floor a number 5 answers

  • value | 0 value | 0 means "convert value to an integer"

    | is the bitwise OR operator.

    To work it first converts the values on both sides to signed 32bit integers then it does a bitwise OR of the values. Since bitwise OR with 0 does nothing this has the effect of just converting to an integer.

    It is different that Math.floor in that it converts toward zero

              | Math.floor | Math.ceil | Math.trunc | | 0  |
    ----------+------------+-----------+------------+------+
       2.5    |     2      |     3     |     2      |   2  |
    ----------+------------+-----------+------------+------+
       1.5    |     1      |     2     |     1      |   1  |
    ----------+------------+-----------+------------+------+
       0.5    |     0      |     1     |     0      |   0  |
    ----------+------------+-----------+------------+------+
      -0.5    |    -1      |     0     |     0      |   0  |
    ----------+------------+-----------+------------+------+
      -1.5    |    -2      |    -1     |    -1      |  -1  |
    ----------+------------+-----------+------------+------+
      -2.5    |    -3      |    -2     |    -2      |  -2  |
    ----------+------------+-----------+------------+------+
     Infinity |  Infinity  |  Infinity |  Infinity  |   0  |
    ----------+------------+-----------+------------+------+
       NaN    |    NaN     |    NaN    |    NaN     |   0  |
    ----------+------------+-----------+------------+------+
     2**32+5  | 4294967301 |4294967301 | 4294967301 |   5  |
    ----------+------------+-----------+------------+------+
    

    That last one, 2*32+5 is a value that does not fit in 32 bits to point out you need to know when | 0 | 0 is appropriate and when it's not.

    | 0 | 0 is also significantly faster than Math.floor or Math.ceil . There may be many reasons it's faster the most obvious is it's an operator, not a function on the Math object which can be replaced and therefore has to be checked on each usage.

    It has a very low precedence which means you can usually tack it on to the end of an expressions without parenthesis

     integerResult = someValue / someOtherValue | 0;
    
    链接地址: http://www.djcxy.com/p/77446.html

    上一篇: JavaScript新手

    下一篇: 0“的意思是在JavaScript中