You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中判断数值是否为偶数时isEven始终返回false如何解决

问题原因
  • 核心问题是赋值运算符与相等运算符的误用:你在if/else分支中使用的==是相等比较运算符,仅会返回布尔比较结果,不会对this.isEven变量执行赋值操作,因此isEven始终保持初始化时的false值,不会随checkNumber的变化更新。
解决方法

方案1:直接修正运算符

将if/else分支内的==替换为赋值运算符=即可正常运行,修改后代码如下:

isEven = false;

increaseLength(event: any){
  this.checkNumber = this.checkNumber + 1;
  if(this.checkNumber % 2 != 0){
    this.isEven = false;
  } else {
    this.isEven = true;
  }
  console.log(this.isEven);
}

方案2:简化代码(更推荐)

可以直接将取余运算的布尔结果赋值给isEven,无需冗余的if/else判断,代码更简洁易读:

isEven = false;

increaseLength(event: any){
  this.checkNumber += 1;
  this.isEven = this.checkNumber % 2 === 0;
  console.log(this.isEven);
}

内容的提问来源于stack exchange,提问作者user10190607

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 16:54:00