【发布时间】: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