带有单个管道的Javascript条件语句“|” [英] Javascript conditional statement with a single pipe "|"

查看:204
本文介绍了带有单个管道的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 ||.

任何人都可以解释这个谜团吗?

Can anyone shed light on this mystery?

谢谢,
詹姆斯

Thanks, James

推荐答案

这是一个按位OR运算符。它将首先将其转换为32位整数,然后将按位OR运算应用于结果的两个数字。在这个例子中,由于 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条件语句“|”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆