JavaScript | operator [duplicate]

夙愿已清 提交于 2019-12-20 01:40:57

问题


Anyone able to explain what "|" and the value after does? I know the output for 0 creates sets of 13, the numbers, 3, 2, 1, 0. But what about | 1, or | 2.

var i = 52;
while(i--) {
    alert(i/13 | 0);
}

回答1:


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.




回答2:


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 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.




回答3:


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.




回答4:


That is the bitwise OR. In evaluating the expression, the LHS is truncated to an integer and returned, so | is effecively the same as Math.floor().



来源:https://stackoverflow.com/questions/5533387/javascript-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!