“ |”是什么 (单管道)在JavaScript中执行?


148
console.log(0.5 | 0); // 0
console.log(-1 | 0);  // -1
console.log(1 | 0);   // 1

为什么0.5 | 0返回零,但任何整数(包括负数)都返回输入整数?单个管道(“ |”)有什么作用?


12
它有助于防止语法错误提醒您键入的事实。代替||
安德鲁·迈尔斯

Answers:


157

这是按位或
由于按位运算仅对整数有意义,因此将0.5被截断。

0 | xx,对于任何人x


9
这是将浮点数转换为int或使用的好方法parseInt()
MaBi 2015年

5
@MaBi:但是,您应该知道该值已转换为32位整数,因此对于较大的数字将无法正常工作。
Guffa

1
那么可以认为与Floor函数相同吗?
May13ank 2015年

2
仅将其用于按位或。正如@Guffa所说,大量数字将不会表现出预期。例如:248004937500 | 0 = -1103165668
Joseph Connolly

大数字将溢出,因为它们已转换为32位int。
slikts

151

位比较非常简单,几乎无法理解;)看看这个“小问题”

   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

太混乱了!


16
布尔也适用。JS将true解释为1,false解释为0; 所以alert(true | false) //yields 1; alert(true | true) //yields 1; alert(false | true) //yields 1; alert(false | false) //yields 0
gordon 2014年

21

单个管道是按位OR

对每对位执行“或”运算。如果a或b为1,则OR b产生1。

JavaScript在按位运算中会截断所有非整数,因此它的计算方式为0|0,即0。


6
这不能回答问题。(“为什么返回0”)
Kirk Woll

8

本示例将为您提供帮助。

 
    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);

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.