【问题标题】:What is the flaw in my bitwise logic?我的按位逻辑有什么缺陷?
【发布时间】:2015-10-19 23:37:31
【问题描述】:

从我的评论中很容易看出我在函数开始时尝试做的事情

    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.dxthis.dy 都为零时,函数的其余部分正在执行。

这里发生了什么?

【问题讨论】:

  • 当您的意思是 == 时,您使用的是 !=。如果它们 都是 都为零,则您想要返回,因此如果 this.dx | this.dy 等于 0。musicly_ut 还指出了优先级错误。我个人会写if (this.dx == 0 && this.dy == 0),因为它更容易阅读......

标签: javascript optimization binary bit-manipulation bitwise-operators


【解决方案1】:

问题是条件执行为:

this.dx | (this.dy != 0)

试试这个:

if (!(this.dx | this.dy)) return;

【讨论】:

    【解决方案2】:

    根据precedence table,在完成不等式检查后将执行按位或。例如:

    [JS]> 0 | 0 == 0
    1
    

    因此,您的表达式实际上被执行为:

    if (this.dx | (this.dy != 0)) { ... }
    

    要解决此问题,请将按位 OR 括起来:if ((this.dx | this.dy) != 0)


    另外,正如@Jon-Skeet 指出的那样,正确的检查可能应该使用==

    【讨论】:

    • 我应该使用!== 来获得额外的保护吗?
    • @LarryPage 在这种情况下您可以使用其中任何一种,但我个人更喜欢尽可能使用===!==,因为我发现它们更容易推理。
    猜你喜欢
    • 1970-01-01
    • 2017-07-16
    • 2011-08-23
    • 2015-07-06
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    相关资源
    最近更新 更多