Mat*_*rym 138 javascript
console.log(0.5 | 0); // 0
console.log(-1 | 0); // -1
console.log(1 | 0); // 1
Run Code Online (Sandbox Code Playgroud)
为什么0.5 | 0返回零,但任何整数(包括负数)都返回输入整数?单管("|")做什么?
Tre*_*rey 146
位比较如此简单,几乎是不可理解的;)看看这个"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)
Run Code Online (Sandbox Code Playgroud)
按位ORing 6和10将给你14:
alert(6 | 10); // should show 14
Run Code Online (Sandbox Code Playgroud)
非常混乱!
这个例子对你有帮助.
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);Run Code Online (Sandbox Code Playgroud)