console.log(0.5 | 0); // 0
console.log(-1 | 0); // -1
console.log(1 | 0); // 1
为什么0.5 | 0
返回零,但任何整数(包括负数)都返回输入整数?单管(“|”)有什么作用?
console.log(0.5 | 0); // 0
console.log(-1 | 0); // -1
console.log(1 | 0); // 1
为什么0.5 | 0
返回零,但任何整数(包括负数)都返回输入整数?单管(“|”)有什么作用?
这是一个按位或。
由于按位运算仅对整数有意义,因此0.5
被截断。
x | 0
is x
, ifx
是一个整数。
位比较是如此简单,几乎无法理解;) 看看这个“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
非常混乱!
这个例子会帮助你。
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