JS For loop logic help

Hi all, I’m working on a small Angular project. Its a quiz app which uses a array called answers to validate the input answer but for some reason I’m failing to get the logic to display the dialog boxes accordingly. the code below is within a submit function. the problem I have is that the loop overwrites itself and even when the answer is found it will still execute the else statement.


 let type = (<HTMLInputElement>document.getElementById('a')).value;

    this.test = type;

    for(let i = 0; i < this.answers.length; i++){

      if(this.test == this.answers[i]){

        this.dialog.open(SuccessboxComponent);

      }else{

        this.dialog.open(FailboxComponent);

     }

  }

Maybe you could try using “===” instead “==”, others seem fine. Also test other parts of your code, maybe there can be error.


still get the same error, perhaps I’ll have to figure out a more elegant method of validating the correct answer

this will open a dialogue for each element inside this.answers

consider carefully, when do you want the success dialogue? when do you want the failure one?

I initialized a variable called result to an empty string then used a break in order to force the loop to stop if it finds the right answer in the array instead of continuing and eventually overwriting itself, i don’t believe its the most efficient way but it gets the job done with no error.

for(let i = 0; i < this.answers.length; i++){

  if(this.test == this.answers[i]){

    this.result = "pass";

    break

  }else if(this.test != this.answers[i]){

    this.result = "fail";

  }

}

if(this.result == "pass"){

  this.dialog.open(SuccessboxComponent);

}else{

  this.dialog.open(FailboxComponent);

}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.