Stack Overflow

This question already has an answer here:

  • Using bitwise OR 0 to floor a number 5 answers

  • This is a clever way of accomplishing the same effect as:

    Math.floor(i/13);
    

    JavaScript developers seem to be good at these kinds of things :)

    In JavaScript, all numbers are floating point. There is no integer type. So even when you do:

     var i = 1;
    

    i is really the floating point number 1.0 . So if you just did i/13 , you'd end up with a fractional portion of it, and the output would be 3.846... for example.

    When using the bitwise or operator in JavaScript, the runtime has to convert the operands to 32 bit integers before it can proceed. Doing this chops away the fractional part, leaving you with just an integer left behind. Bitwise or of zero is a no op (well, a no op in a language that has true integers) but has the side effect of flooring in JavaScript.


    It is the bitwise OR operator. There is both an explanation and an example over at MDC. Since doing bitwise OR with one operand being 0 produces the value of the other operand, in this case it does exactly nothing rounds the result of the division down.

    If it were written | 1 | 1 what it would do is always print odd numbers (because it would set the 1-bit to on); specifically, it would cause even numbers to be incremented by 1 while leaving odd numbers untouched.

    Update: As the commenters correctly state, the bitwise operator causes both operands to be treated as integers, therefore removing any fraction of the division result. I stand corrected.


    It's a bitwise operator. Specifically the OR Bitwise Operator.

    What it basically does is use your var as an array of bits and each corresponding bit is with eachother. The result is 1 if any of them is 1. And 0 if both are 0.

    Example:

    24 = 11000

    10 = 1010

    The two aren't of equal length so we pad with 0's

    24 = 11000

    10 = 01010


    26 = 11010

    24 | 10 = 26

    Best way to learn this is to readup on it.

    链接地址: http://www.djcxy.com/p/77432.html

    上一篇: 数学中的Javascript管道可以在不使用Math.floor的情况下获得Math.floor

    下一篇: 堆栈溢出