Javascript 我的位逻辑有什么缺陷?
从我的评论中很容易看出我在函数开始时试图做什么Javascript 我的位逻辑有什么缺陷?,javascript,optimization,binary,bit-manipulation,bitwise-operators,Javascript,Optimization,Binary,Bit Manipulation,Bitwise Operators,从我的评论中很容易看出我在函数开始时试图做什么 this.move = function ( ) { if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero 也就是说,如果(this.dx==0&&this.dy==0),我需要与之等价的。我认为按位的或是正确的,因为this.dx | this.dy不等于零当且仅当this.dx至少有一位打开
this.move = function ( )
{
if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero
也就是说,如果(this.dx==0&&this.dy==0),我需要与之等价的。我认为按位的或是正确的,因为this.dx | this.dy
不等于零
当且仅当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
均为零时,函数的其余部分正在执行
这是怎么回事 根据不平等性检查完成后,按位OR将执行。例如:
[JS]> 0 | 0 == 0
1
因此,您的表达式实际上执行为:
if (this.dx | (this.dy != 0)) { ... }
this.dx | (this.dy != 0)
若要解决此问题,请将按位OR括起来:if((this.dx | this.dy)!=0)
此外,正如@Jon Skeet所指出的,正确的检查可能应该根据位的顺序使用==
,或者在不平等检查完成后执行。例如:
[JS]> 0 | 0 == 0
1
因此,您的表达式实际上执行为:
if (this.dx | (this.dy != 0)) { ... }
this.dx | (this.dy != 0)
若要解决此问题,请将按位OR括起来:if((this.dx | this.dy)!=0)
此外,正如@Jon Skeet所指出的,正确的检查可能应该是使用=
问题是执行条件如下:
if (this.dx | (this.dy != 0)) { ... }
this.dx | (this.dy != 0)
试试这个:
if (!(this.dx | this.dy)) return;
问题是条件的执行方式如下:
if (this.dx | (this.dy != 0)) { ... }
this.dx | (this.dy != 0)
试试这个:
if (!(this.dx | this.dy)) return;
您正在使用=代码>当您的意思是==
时。如果它们都为零,则需要返回,因此如果this.dx | this.dy
等于0。还有音乐上指出的优先错误。就我个人而言,如果(this.dx==0&&this.dy==0)
读起来更清晰,我会写,因为您使用的是=代码>当您的意思是==
时。如果它们都为零,则需要返回,因此如果this.dx | this.dy
等于0。还有音乐上指出的优先错误。就我个人而言,如果(this.dx==0&&this.dy==0)
读起来更清晰,我会写,我应该写==
额外的保护层?@LarryPage在这种情况下你可以使用,但我个人更喜欢使用==
或==代码>只要可能,因为我发现它们更容易推理。我应该做==
额外的保护层?@LarryPage在这种情况下你可以使用,但我个人更喜欢使用==
或==代码>只要可能,因为我发现它们更容易推理。