Home > OS >  Break out of while loop that has an array inside
Break out of while loop that has an array inside

Time:12-21

Want to let the user make an array until they press cancel on the prompt But the nested if statement won't trigger and break the while loop.

The goal of the program is to show the first ten items in the array with the message 'Only the first ten guests will be recorded' This is part of my course which is why I am letting the user input as much as they like and then reducing it to 10 after.

let guests = []
i = 1
j = 1

while (j = 1) {
    input = guests.push(prompt('Enter Guest'   i   '(press cancel to stop)'))
    i  

    if(input === null) {
        j  
        //break;
    }
}

if (guests.length > 10) {
    console.log('Only the first ten guests will be recorded')

    while (guests.length > 10) {
        guests.pop()
    }
}

console.log(guests)

If I remove the if() brackets the program stops after the user inputs one array item

And if I try break; it stops after the user types in 1 array item.

I have also tried adding

    else {
        continue;
    }

but to no avail

CodePudding user response:

Store the result of prompt to test for null (instead of comparing the return value of Array#push).

while (true) {
    input = prompt('Enter Guest'   i   '(press cancel to stop)');
    if(input === null) break;
    guests.push(input);
    i  ;
}
  • Related