`Math.trunc` vs `|0` vs `<<0>>0` vs `&-1` vs `^0`

后端 未结 2 1004
梦谈多话
梦谈多话 2020-12-19 08:16

I have just found that in ES6 there\'s a new math method: Math.trunc.

I have read its description in MDN article, and it sounds like using |0

2条回答
  •  生来不讨喜
    2020-12-19 08:37

    In many programming languages with bitwise operators, attempting to do a bitwise operation on a non-integer is a type error:

    >>> # Python
    >>> 1 << 0; 1.2 << 0
    1
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unsupported operand type(s) for <<: 'float' and 'int'
    

    In ECMA-262, a Number is a double-precision 64-bit binary format IEEE 754. In other words, there are no integers in JavaScript. As long as the values you're dealing with fit within -(Math.pow(2,32)) and Math.pow(2,31) then the bitwise operations are a fast way to truncate floating point values. All of the different bitwise operations do different things, but in every example here they're essentially doing an identity operation. The critical difference is that JavaScript does a ToInt32 operation on the value before doing the nothing else part.

    Bitwise identity operations:

    i |  0 // For each bit that is 1, return 1|0. For each bit that is 0, return 0|0.
    i ^  0 // xor, but effectively same as previous.
    i << 0 // Shift the value left zero bits.
    i >> 0 // Shift the value right zero bits.
    i & -1 // Identity mask
    ~~i    // Not not - I had forgotten this one above.
    

提交回复
热议问题