为什么空输入值等于 true?

Why an empty input value equal to true?

如果输入等于答案,则假设此代码执行 oninput。 相反,如果我有一个等于 0 的乘法问题,一旦我从上一个乘法问题中删除答案(将输入留空),结果就会返回 true 并执行 if 语句。我该如何防止这种情况?

 ngOnInit() { this.multiply(); }
  f1 =  0;
  f2 =  0;
  answer:number = 0;
  input:number = 0;
 
  multiply():void{
    this.f1 = Math.floor(Math.random() * 12);
    this.f2 = Math.floor(Math.random() * 12);

    this.answer = this.f1 * this.f2;

    console.log(this.answer);
  }

  checkAnswer(event){
      this.input = event.target.value;

      if(this.input == this.answer){
        console.log(this.input + " " + "is correct!");

        this.multiply();
      } else{
        console.log(this.input + " " + "is incorrect" + " "  + this.answer);
      }
    }
}

使用===代替==

所以你的 if 语句应该是

if(this.input === this.answer){

解释:

  • == 只比较 value 而不是 datatype
  • === 比较值和数据类型

示例:

  • '' == 0 => true(正确,因为 == 只检查值)
  • '' === 0 => false (错误因为 === 检查值及其数据类型)

Here, you can read about the difference between == and ===

如果语句为真,则重置输入值。

event.target.value = null;

防止用户触发输入事件以清除输入。因此不必 运行 checkAnswer 函数 if this.answer === 0 and this.input === " ";