Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
Can't get value of array

Still can't understand my mistake with this code. All what I want it - via prompt get all list of users (name / surname)

function UserList() {
  let users = [];
  while (true) {
    let response = prompt('Please, enter your name surname?');
    if (response == null) {
      alert('cancel');
      break;
    }
    users.push(response.split(' '));
  }
  return users;
}

function User() {
  this.name = userList[0];
  this.surname = userList[1];
  this.regDate = new Date;
  for (i = 0; i < userList.length; ++i) {
    console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
  }
}

let userList = new UserList();
let user = new User();

And I faced with a misunderstanding why I cant get first word of prompt despite I put users.push (response.split(' ')). userList [0] - shows first index of array instead first word.

And second I want to get all list of users in console.log but instead it I get the same string depending on length of array

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

userList[0] in the function User will return an array: ['name', 'surname']. To get the first name for example, you need to use this.name = userList[i][0]

function UserList() {
    let users = [];
    while (true) {
        let response = prompt('Please, enter your name surname?');
        if (response == null) {
            alert('cancel');
            break;
        }
        users.push(response.split(' '));
    }
    return users;
}

function User() {
    for (var i = 0; i < userList.length; ++i) {
        this.name = userList[i][0];
        this.surname = userList[i][1];
        this.regDate = new Date;
        console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
    }    
}

let userList = new UserList();
let user = new User();
about 4 years ago · Juan Pablo Isaza Relatório

0

  1. UserList shouldn't be a constructor. It should just be a function that returns an array of names.

  2. You shouldn't be iterating over the list of users within User. You should then be iterating over the array creating one new User on each iteration which should be generated from a constructor. You can just pass in each name from the array and build an new object.

function getNames() {
  const users = [];
  while (true) {
    const response = prompt('Please, enter your first and last names');
    if (response == null) break;
    users.push(response.split(' '));
  }
  return users;
}

// Pass in a user name from the array as an argument
// It's array so we can destructure the first and last name
// immediately
function User([first, last]) {
  this.first = first;
  this.last = last;
  this.regDate = new Date();
  this.message = `Name: ${this.first}. Surname: ${this.last}. Date of registration: ${this.regDate}.`;
}

// Iterate over the array generated by `getUsers`
// and for each name create a new user.
for (let name of getNames()) {
  console.log(new User(name));
}

Additional documentation

  • Destructuring assignment
about 4 years ago · Juan Pablo Isaza Relatório

0

You are pushing an array in an other array, so your index is not correct (array looks like this: [["firstname", "lastname"]]). You could spread the items when pushing using the spread operator (...), you could also flatten the array using flat().

Also when creating a date, use new Date().

 function UserList() {
   let users = [];
   while (true) {
     let response = prompt('Please, enter your name surname?');
     if (response == null) {
       alert('cancel');
       break;
     }
     users.push(...response.split(' ')); // flatten

   }
   return users;
 }

 function User() {
   this.name = userList[0];
   this.surname = userList[1];
   this.regDate = new Date(); // ()

   console.log('Name: ' + this.name + ' Surname: ' + 
     this.surname + '. Date of registration : ' + this.regDate)
 }

 let userList = new UserList();
 let user = new User();

Using flat()

return users.flat();

Edit

I actually understood the question wrong (thought you only wanted 1 user), the other answer should be correct and makes more sense.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda