我的按位逻辑有什么缺陷?
What is the flaw in my bitwise logic?
从我的评论中可以很容易地看出我在函数开始时尝试做的事情
this.move = function ( )
{
if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero
也就是说,我想要 if (this.dx == 0 && this.dy == 0)
的等价物。我认为按位 OR
是正确的,因为 this.dx | this.dy
不等于 zero
当且仅当 this.dx
至少有一位或 this.dy
至少有一位(或两者都至少有一位)。但我一定是错的,因为我的测试
this.move = function ( )
{
console.log("this.dx = " + this.dx + ", this.dy = " + this.dy); // TEST
if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero
表示当 this.dx
和 this.dy
均为零时,函数的其余部分正在执行。
这是怎么回事?
根据precedence table不等式检查完成后将执行按位或运算。例如:
[JS]> 0 | 0 == 0
1
因此,您的表达式实际上执行为:
if (this.dx | (this.dy != 0)) { ... }
要解决此问题,请将按位或括号括起来:if ((this.dx | this.dy) != 0)
。
此外,正如@Jon-Skeet 指出的那样,正确的检查可能应该是 ==
。
问题是条件执行为:
this.dx | (this.dy != 0)
试试这个:
if (!(this.dx | this.dy)) return;
从我的评论中可以很容易地看出我在函数开始时尝试做的事情
this.move = function ( )
{
if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero
也就是说,我想要 if (this.dx == 0 && this.dy == 0)
的等价物。我认为按位 OR
是正确的,因为 this.dx | this.dy
不等于 zero
当且仅当 this.dx
至少有一位或 this.dy
至少有一位(或两者都至少有一位)。但我一定是错的,因为我的测试
this.move = function ( )
{
console.log("this.dx = " + this.dx + ", this.dy = " + this.dy); // TEST
if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero
表示当 this.dx
和 this.dy
均为零时,函数的其余部分正在执行。
这是怎么回事?
根据precedence table不等式检查完成后将执行按位或运算。例如:
[JS]> 0 | 0 == 0
1
因此,您的表达式实际上执行为:
if (this.dx | (this.dy != 0)) { ... }
要解决此问题,请将按位或括号括起来:if ((this.dx | this.dy) != 0)
。
此外,正如@Jon-Skeet 指出的那样,正确的检查可能应该是 ==
。
问题是条件执行为:
this.dx | (this.dy != 0)
试试这个:
if (!(this.dx | this.dy)) return;