skip to Main Content

I need to create a program which asks a user to input a list of names and each name should be added to an array and the user can only input 10 names maximum and if they try to input more a message needs to come up and say that they have already have ten names and then output those ten names. I am struggling with the outputs

let inputArray = [];
let size = 11;

for(let i = 0; i < size; i++){

    if (i < size) {
        inputArray[i] = prompt("Please enter the name of 10 people 
                                 you would like to invite to a party" 
                                 + (i+1));
    } else if (i = 11) {
        console.log("You have already invited 10 people");
    }
}
console.log(inputArray);

2

Answers


  1. try this

    let inputArray = [];
    let maxSize = 10;
    
    for (let i = 0; i < maxSize; i++) {
      let name = prompt(`Please enter name ${i+1} of ${maxSize}:`);
      if (name !== null) {
        inputArray.push(name);
      } else {
        console.log("You have cancelled the input process.");
        break;
      }
    }
    
    if (inputArray.length === maxSize) {
      console.log("You have reached the maximum number of names.");
    } 
    
    console.log("The names you have entered are: ");
    console.log(inputArray);
    
    Login or Signup to reply.
  2. Try this out and see if it works for you.

    let limit = 3
    let arr = new Array(limit), size = 11;
    
    for(let i=0; i<size; i++){
        let inpttext = prompt("Please enter the name of 10 people.");
        if(i < arr.length){
            arr.push(inpttext);
        }else{
            console.log("You have already invited 10 people.")
            break;
        }   
    }
    
    console.log(arr)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search