如何解决JavaScript中的“ |”单管道有什么作用?
|console.log(0.5 | 0); // 0
console.log(-1 | 0); // -1
console.log(1 | 0); // 1
为什么0.5 | 0
返回零,但是任何整数(包括负数)都返回输入整数?单个管道(\“ | \”)有什么作用?
解决方法
这是按位或。
由于按位运算仅对整数有意义,因此
0.5
将被截断。
对于任何x
,3ѭ是x
。
, 位比较是如此简单,几乎是难以理解的;)看看这个“ 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
太混乱了!
, 单个管道是按位或。
对每对执行“或”运算
位。如果一个a或b产生1
或b为1。
JavaScript在按位运算中会截断任何非整数,因此其计算方式为0|0
,即0。
, 本示例将为您提供帮助。
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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。