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

211
Visualizações
Trying to push a string into an array returned from another function

Hey I'm pretty new to coding. I've tried looking around for how to do this but am at a loss.

Below are the two functions, which are in an object.

listPeople: function () {
    let array = []
    return array;
    // returns an array of all people for whom tasks exist
},
add: function ( name, task ) {
    return this.listPeople().push( name )
},

If I run this, the add function returns 1. and will return 2 if I push two things in, and so on. What's going on here, how do i push the name variable from add into the array in listpeople?? The name variable is 'zeke' by the way.

Sorry in advance if this doesn't make sense :D

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

0

It should probably look more like this. Create an arr property, and push objects into it from add. You can then return that list from listPeople.

const obj = {
  arr: [],
  listPeople: function() {
    return this.arr;
  },
  add: function(name, task) {
    return this.arr.push({ [name]: task });
  }
}

obj.add('bob', 'Shopping');
obj.add('Betty', 'Singing');
console.log(obj.listPeople());

about 4 years ago · Juan Pablo Isaza Relatório

0

What's happening in your code is that the add function is returning the result of the .push() method (the new length of the array).

If your intent is to actually return the array, you should modify the add method as follows:

add: function ( name, task ) {
    var people = this.listPeople();
    people.push(name);
    return people;
},

Additionally, while changing listPeople to an array property instead of a method may work better on a shallow level, I don't know what you may have planned to implement into the listPeople method. And it may only confuse/complicate things as far as answering the question you have asked.

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