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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6194950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:41:04  来源:igfitidea点击:

What does the "|" (single pipe) do in JavaScript?

javascript

提问by Matrym

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

Why does 0.5 | 0return zero, but any integer (including negative) returns the input integer? What does the single pipe ("|") do?

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

回答by SLaks

This is a bitwise or.
Since bitwise operations only make sense on integers, 0.5is truncated.

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

0 | xis x, for any x.

0 | xx,对于任何x

回答by Trey

Bit comparison is so simple it's almost incomprehensible ;) Check out this "nybble"

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

Bitwise ORing 6 and 10 will give you 14:

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

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

Terribly confusing!

非常混乱!

回答by Yahel

A single pipe is a bit-wise OR.

单个管道是按位 OR

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1.

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

JavaScript truncates any non-integer numbers in bitwise operations, so its computed as 0|0, which is 0.

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

回答by Nikhil Mahirrao

This example will help you.

这个例子会帮助你。

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