带有单管道“|"的 Javascript 条件语句
只是想知道以前是否有人遇到过这种情况.
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
}
它没有错误,所以似乎有效.但是,我和一位同事从未见过单管道 |
的 OR 语句,只有 2 个 ||
.
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 ||
.
谁能解开这个谜团?
谢谢,詹姆斯
推荐答案
这是一个按位或运算符.它将首先将其转换为 32 位整数,然后将按位或运算应用于结果的两个数字.在这种情况下,由于 Boolean(1)
为真且 Number(true)
为 1,因此它可以正常工作而不会出现问题(==
运算符将始终返回一个布尔值,而 if 语句将任何内容转换为布尔值).以下是其工作原理的几个示例:
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)
由于双方都必须转换为数字(并因此进行评估),因此在本应使用逻辑 OR 语句 (||
) 时使用数字时,这可能会导致意外结果.为此,请举几个例子:
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!
参考:http://www.ecma-international.org/ecma-262/5.1/#sec-11.10
相关文章