Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This code is suppose to execute oninput if the input is equal to the answer. Instead, if i have a multiplication problem that equals 0, once i delete the answer from the previous multiplcation problem (leaving the input empty), the result comes back true and executes the if statement. How can i prevent this?

 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);
      }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
202 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use === instead of ==

So your if statement should be

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

Explanation:

  • == only compares the value and not datatype
  • === compares the value and datatype both

Examples:

  • '' == 0 => true (true because == only checks the value)
  • '' === 0 => false (false because === checks both the value and its datatype)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...