“|”是什么意思 (单管道)在 JavaScript 中做什么?

IT技术 javascript
2021-01-23 22:47:09
console.log(0.5 | 0); // 0
console.log(-1 | 0);  // -1
console.log(1 | 0);   // 1

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

5个回答

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

x | 0is x, ifx是一个整数。

仅将其用于按位或。正如@Guffa 所说,大量的行为不会像预期的那样。例如:248004937500 | 0 = -1103165668
2021-03-15 22:47:09
这是将浮点数转换为 int 的好方法,或者使用 parseInt()
2021-03-25 22:47:09
@MaBi:但是,您应该知道该值已转换为 32 位整数,因此对于较大的数字将无法正常工作。
2021-04-01 22:47:09
那么可以认为是同Floor函数吗?
2021-04-07 22:47:09
大数会溢出,因为它们被转换为 32 位 int。
2021-04-09 22:47:09

位比较是如此简单,几乎无法理解;) 看看这个“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

非常混乱!

也适用于布尔值。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
2021-03-15 22:47:09

单个管道是按位 OR

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

JavaScript 在按位运算中截断任何非整数,因此其计算为0|0,即 0。

这不能回答问题。(“为什么这会返回 0”)
2021-04-05 22:47:09

这个例子会帮助你。

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 位整数并由一系列位(零和一)表示。超过 32 位的数字将丢弃其最高有效位。

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

= 0.5 | 0
= 0   | 0
= 0