“ |”(单管道)在 JavaScript 中起什么作用?

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

为什么 0.5 | 0返回零,而任何整数(包括负数)返回输入整数?单管(“ |”)做什么?

102019 次浏览

单管是 位智能手术室(位智能手术室)

对每一对执行 OR 操作 或 b 产生1,如果 a 或者 b 是1。

JavaScript 在按位运算中截断任何非整数数字,因此它的计算结果为 0|0,即0。

这是 按位或
因为按位操作只对整数有意义,所以 0.5被截断。

如果 x是一个整数,则 x | 0x

比特比较是如此简单,简直难以理解;)看看这个“ 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)

按位 ORing 6和10将给你14:

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

非常混乱!

这个例子会帮助你。

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

这是 Bitwsie OR (|)

操作数被转换为32位整数,并由一系列位(0和1)表示。超过32位的数字会丢弃其最重要的位。

因此,在我们的例子中,十进制数被转换为整数0.5到0。

= 0.5 | 0
= 0   | 0
= 0