【问题标题】:boolean set to false; returns true on if statement without ==布尔值设置为假;在没有 == 的 if 语句上返回 true
【发布时间】:2017-09-22 14:46:43
【问题描述】:

我有一个角度组件,它有一个共同级别的布尔变量和一个 onClick 事件。 html 文件如下所示:

<div class="divClass" (click)="onClick($event)"></div>

ts文件中的相关代码如下:

export class myComponent implements OnInit {

  guardFirst : boolean;
  guardSecond : Boolean;

  constructor(...) {
    this.guardFirst = false;
    this.guardSecond = false;
  }

  onClick( ev : MouseEvent ) {

    if (this.guardFirst) {
      if (this.guardSecond) {
        console.log("first guard: " + this.guardFirst + "; second guard: " + this.guardSecond);
        // the logic takes place here
      }
      this.guardSecond = true;
    }
    this.guardFirst = true;
  }

}

我显然改变了实际代码,因为它是专有的,但结构是相同的。您希望在第三次单击 div 之前不会发生逻辑和控制台日志记录,但它会在第一次单击时发生。控制台为这两个变量记录了 false,但不知何故通过了两个 if 语句来到达那里,根据其他语言的工作方式,人们期望返回 false。经过大量调试和控制台日志记录以检查值和流程后,我最终想到了像这样更改代码:

onClick( ev : MouseEvent ) {

  if (this.guardFirst == true) {
    if (this.guardSecond == true) {
      console.log("first guard: " + this.guardFirst + "; second guard: " + this.guardSecond);
      // the logic takes place here
    }
    this.guardSecond = true;
  }
  this.guardFirst = true;
}

这告诉我,没有值等价语句的布尔值在它们不为 null 或未定义时返回 true; false 或 true,只要有赋值,就返回 true。由于我的代码将布尔值既作为原语又作为对象,这不是这种行为的原因。我尝试在没有 Angular 的 Typescript 中在 jsfiddle 上测试类似的东西,它的工作方式符合我的预期(如果值为 false,则返回 false,无论是否缺少 ==)。

谁能给我解释一下这个现象?它从何而来?似乎它必须是一个 Angular 的东西 - 是真的吗?这是否总是在 Angular 中以这种方式工作,还是我的项目有问题?这是预期的行为吗?如果是这样,为什么开发人员会做出这个决定?如果不是,为什么会这样?

提前致谢。

编辑:修正了自我/这个错字。对于投票结束该问题的任何人,请尝试发表评论以解释您认为应该关闭该问题的原因,以及如何更改它以符合您对 SO 指南的理解。

【问题讨论】:

  • 不应该是this.guardFirst吗?
  • 你能说明你在哪里定义自我吗?
  • 你说得对,就是this.guard。首先,我在将代码转录到stackoverflow上时出错了。我一直在用 Swift 做另一个项目,结果搞混了

标签: angular typescript if-statement boolean-expression


【解决方案1】:

我认为@oreofeolurin 可能是对的。我不认为这是一个角度特定的问题,而是一个使用 self 而不是这个的 javascript/typescript 问题。

这里有一个 plunker 来演示: https://plnkr.co/edit/SzNQyHvyLVjfN9Fm6GER?p=preview

 <div class="divClass" (click)="onClick($event)">Click me</div>
 <div>Clicks: {{clicks}} </div>


clicks = 0;

  guardFirst : boolean;
  guardSecond : Boolean;

  constructor() {
    this.guardFirst = false;
    this.guardSecond = false;
  }

  onClick( ev : MouseEvent ) {

    this.clicks++;

    if (this.guardFirst) {
      if (this.guardSecond) {
        alert("hi");
      }
      this.guardSecond = true;
    }
    this.guardFirst = true;
  }
}

【讨论】:

  • 这是我在将代码移动到 SO 时犯的错字,请忽略。我的实际代码使用这个。
  • 在那种情况下,你能检查一下我包含的 plunker 吗?它似乎按照您想要的方式工作。我的代码和你希望的有区别吗?也许您没有像在生产环境中那样在代码示例中准确地重现问题?
猜你喜欢
  • 1970-01-01
  • 2014-12-19
  • 2020-06-23
  • 2022-12-17
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
相关资源
最近更新 更多