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
是整数,则x | 0
等同于x
。
parseInt()
函数。 - MaBi位比较如此简单,以至于几乎难以理解 ;) 看看这个“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
非常混乱!
alert(true | false) //输出1; alert(true | true) //输出1; alert(false | true) //输出1; alert(false | false) //输出0
。 - gordon这个例子将会对您有所帮助。
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
TypeError:unsupported operand type(s) for |: 'float' and 'int'
。 - Serge Stroobandt