Home > front end >  Can anyone please show me how to use the .push() method for an array?
Can anyone please show me how to use the .push() method for an array?

Time:12-21

  • Ask the user to input names of people they would like to invite to a dinner party.
  • Each name should be added to an array.
  • The user can only invite a maximum of ten people. If they try to add more than 10 names, the program should state, “You have already added 10 people to your guest list.”
  • The program should then output the list.

I am trying to solve this task, I am not sure if I am doing it properly. I am a beginner so I will appreciate any help or hints.

{
    let list = [];
    list.length = 10
    while(true){
      let input = prompt("Add a guest");
      if(input <= 10 || input == null){ 
        break;  //arr.slice(0,10) 
      }
      list.push(String(input));
      console.log(list);
    }
}

CodePudding user response:

Loop through; if the user inputs nothing I assume they are "done" - not stated in the requirements how to manage this.

I put this in a function to call passing the max count but that was not specifically stated here in the requirements.

Just loop until the conditions are met.

function addGuests(maxGuests = 10) {
  const tooMany = "You have already added 10 people to your guest list.";
  const promptText = "Add a guest";
  let list = [];
  let hasGuest = true;
  while (list.length < maxGuests && hasGuest) {
    let guests = prompt(promptText);
    if (guests != null && guests.trim().length > 0) {
      list.push(String(guests));
      console.log("L:", list);
    } else {
      hasGuest = false;
    }
    if (list.length >= maxGuests) {
      alert(tooMany);
    }
  }
  return list;
}
let guests = addGuests(10);
console.log(guests, guests.length);

CodePudding user response:

Try something like:

const readLineSync = require('readline-sync');

const arr = [];

while (arr.length < 10) {
    const guest = readLineSync.question('Add a guest: ');

    if (guest) {
        arr.push(guest);
    }
}

console.log('You have added 10 people...');
console.log(arr);

This uses the readline-sync module to get input from the user, starts off with an empty array and keeps pushing non-empty input values to it until the length of that array is 10. It then prints out the items in the array to the console.

  • Related