Javascript conditional statement with a single pipe quot;|quot;(带有单管道“|的 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
这篇关于带有单管道“|"的 Javascript 条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有单管道“|"的 Javascript 条件语句
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06