Home > front end >  how to make the statement to repeat itself until it gets true?
how to make the statement to repeat itself until it gets true?

Time:01-14

I want this statement to repeat itself until the condition is true, forgot the syntax to do so

let gradeAmount = Number(prompt('insert a number between 1 and 5'));
const grades = [];
if (gradeAmount >= 1 && gradeAmount <= 5) {
  for (let i = 0; i < gradeAmount; i  ) {
    const grade = Number(prompt('insert the grade'));

    grades.push(grade);
  }
} else {
  alert('invalid number of grades, please insert again');
  gradeAmount = Number(prompt('insert a number between 1 and 5'));
}

CodePudding user response:

A possible solution is to use do...while. This code will keep display alert('invalid number of grades, please insert again') and window.prompt until it meets you condition. Then it will window.prompt for user to enter the number.

const grades = [];
let gradeAmount = Number(prompt('insert a number between 1 and 5'));
do{
if(gradeAmount < 1 || gradeAmount > 5){
alert('invalid number of grades, please insert again');
  gradeAmount = Number(prompt('insert a number between 1 and 5'));
  }
 }
 
 while(gradeAmount < 1 || gradeAmount > 5)
 
 
   for (let i = 0; i < gradeAmount; i  ) {
    const grade = Number(prompt('insert the grade'));

    grades.push(grade);
  }
  console.log(grades)

  •  Tags:  
  • Related