Javascript conditional statement with a single pipe “|”

倾然丶 夕夏残阳落幕 提交于 2019-12-17 21:16:11

问题


Just wondering if anyone has come across this before.

I found in a project (that was handed over from another developer) a conditional statement that looked something like this:

if (variableOne == true | variable2 == true) {
    // Do something here
}

It didn't error, so seems to work. But, myself and a colleague have never seen an OR statement with a single pipe |, only 2 ||.

Can anyone shed light on this mystery?

Thanks, James


回答1:


This is a bitwise OR operator. It will first convert it into a 32 bit integer, then apply the bitwise OR operation to the two numbers that result. In this instance, since Boolean(1) is true and Number(true) is 1, it will work fine without issue (the == operator will always return a boolean, and a if statement converts anything to a boolean). Here are a few examples of how it works:

1 | 0; // 1
0 | 0; // 0
0 | 1; // 1
1 | 1; // 1
true | false; // 1
false | false; // 0
2 | 1; // 3 (00000010, 00000001) -> (00000011)

As both sides have to be converted to a number (and therefore evaluated), this may cause unexpected results when using numbers when the logical OR statement (||) was meant to be used. For this, take these examples:

var a = 1;
a | (a = 0);
console.log(a); // 0

var b = 1;
b || (b = 0);
console.log(b); // 1

// I wanted the first one
var c = 3 | 4; // oops, 7!

Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-11.10




回答2:


That's a bitwise OR, see the documentation from Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators)




回答3:


The two pipes syntax "||" means it short circuits the logical expression. Evaluating only the needed until it knows the result. What does it means?

if(a==null || a.type=='ok')

If a is null, it will evaluate only the first part of the expression, without errors on javascript side.

if(a==null | a.type=='ok')

If a is null in this case, you will have an error, since it will evaluate the second part of the expression too.

It's the same thing on others C type languages: Java, C,C++ And the same thing applies to '&' and '&&'




回答4:


| is a bitwise OR, which in some very limited cases can substitute the ||.

An important difference is that with | both operands are evaluated, unlike with the || which evaluates the second operand only if the first is false.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators



来源:https://stackoverflow.com/questions/18594940/javascript-conditional-statement-with-a-single-pipe

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