首页 文章

布尔值设置为false;如果语句没有==,则返回true

提问于
浏览
0

我有一个角度组件,有一个copmonent级布尔变量和一个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中是否总是这样,或者与我的项目有关?这是预期的行为吗?如果是这样,为什么开发人员做出这个决定?如果没有,为什么会发生?

提前致谢 .

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

1 回答

  • 0

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

    这是一个演示的掠夺者: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;
      }
    }
    

相关问题