【问题标题】:Why an empty input value equal to true?为什么空输入值等于 true?
【发布时间】:2021-01-11 10:22:43
【问题描述】:

如果输入等于答案,则假设此代码执行 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);
      }
    }
}

【问题讨论】:

  • 试试this.input = event.target.value.trim();
  • 尝试使用 "===" 而不是 "==" 我更新了下面的答案

标签: javascript angular if-statement input null


【解决方案1】:

使用=== 而不是==

所以你的 if 语句应该是

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

说明:

  • == 仅比较 value 而不是 datatype
  • === 同时比较值和数据类型

示例:

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

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

【讨论】:

  • 我尝试了“===”,但没有成功。即使答案是正确的,它也会返回错误。
  • @Creatif_IV 能否请您控制台记录您的答案和输入值并检查它们是否相同?还请在此处提及这两个值。
  • 好的,我现在明白了,我 console.log(typeof this.input)。输入被标识为字符串。 0 和 " "(一个空字符串)返回 "true"。很奇怪。
【解决方案2】:

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

event.target.value = null;

防止用户触发输入事件以清除输入。因此,如果 this.answer === 0 和 this.input === " ";

则不必运行 checkAnswer 函数

【讨论】:

    猜你喜欢
    • 2016-09-17
    • 2013-01-05
    • 1970-01-01
    • 2014-07-04
    • 2021-10-08
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多