JavaScript中的"|"(单竖线)是什么作用?

200
console.log(0.5 | 0); // 0
console.log(-1 | 0);  // -1
console.log(1 | 0);   // 1
为什么0.5 | 0返回零,而任何整数(包括负数)都会返回输入的整数?单个竖线符号(“|”)是什么意思?

21
它有助于避免因为你打了 "|" 而并未警告你的语法错误,而应该是 "||"。 - Andrew Myers
通过在浮点数上使用按位或运算符,您基本上是在依赖JavaScript的不成熟。Python3会引发错误TypeError:unsupported operand type(s) for |: 'float' and 'int' - Serge Stroobandt
5个回答

195

这是一个位或操作。位运算仅适用于整数,因此0.5被截断。

如果x是整数,则x | 0等同于x


12
这是一种不错的将浮点数转换为整数的方法,或者可以使用parseInt()函数。 - MaBi
7
你应该知道该值会被转换为一个32位整数,因此对于较大的数字将无法正常工作。 - Guffa
1
所以可以被认为是和Floor函数一样吗? - May13ank
6
只能用于位或运算。如@Guffa所说,大数的行为可能与预期不同。例如:248004937500 | 0 = -1103165668 - Joseph Connolly
1
大数会溢出,因为它们被转换为32位整数。 - slikts
显示剩余2条评论

166

位比较如此简单,以至于几乎难以理解 ;) 看看这个“nybble”

   8 4 2 1
   -------
   0 1 1 0 = 6  (4 + 2)
   1 0 1 0 = 10 (8 + 2)
   =======
   1 1 1 0 = 14 (8 + 4 + 2)

对6和10进行按位或运算将得到14:

   alert(6 | 10); // should show 14

非常混乱!


17
布尔类型同样适用。JS将true解释为1,false解释为0;所以alert(true | false) //输出1; alert(true | true) //输出1; alert(false | true) //输出1; alert(false | false) //输出0 - gordon

22
一个单独的管道是按位或操作。
执行每对比特的或操作。如果a或b中的任何一个为1,则a或b的结果为1。
JavaScript在按位操作中截断任何非整数数字,因此它被计算为0|0,即0。

7
这并没有回答这个问题。(“为什么这会返回0”) - Kirk Woll

15

这个例子将会对您有所帮助。

var testPipe = function(input) { 
   console.log('input => ' + input);
   console.log('single pipe | => ' + (input | 'fallback'));
   console.log('double pipe || => ' + (input || 'fallback'));
   console.log('-------------------------');
};

testPipe();
testPipe('something'); 
testPipe(50);
testPipe(0);
testPipe(-1);
testPipe(true);
testPipe(false);


0

这是一个Bitwsie OR (|)

操作数被转换为32位整数,并由一系列位(零和一)表示。具有超过32位的数字将丢弃其最高有效位。

因此,在我们的情况下,十进制数被转换为整数0.5到0。

= 0.5 | 0
= 0   | 0
= 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接