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

126
Visualizações
Passing function expression to object returns undefined

I have reviewed similar questions and most seem to concern this, mine doesn't. I am trying to create a new property that is a function expression on objects in an array but the property returns undefined. I need it to return function

Here is a fiddle version.

let athleteArray = [
  rupert = {
    name: 'Mike',
    age: '33',
    sport: 'sitting',
    quote: 'Hello Super nintendo chalmers'
  },

  alice = {
    name: 'Bill',
    age: '35',
    sport: 'cooking',
    quote: 'stop that'
  }
];


const win = function(name, sport) {
  console.log(`${name} won the ${sport} event!`)
}

//loop to add new 'win' property

for (let i = 0; i < athleteArray.length; i++) {
  athleteArray[i].win = win(athleteArray[i].name,
    athleteArray[i].sport)
  console.log(athleteArray[i])
  console.log(typeof(athleteArray[i].win))
}

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

0

Use a class where you can define your methods.

class Person {
  constructor(details) {
     this.name = details.name || 'Unknown';
     this.age = details.age || 'Unknown';
     this.sport = details.sport || 'Unknown';
     this.quote = details.quote || 'Unknown';
  }
  win () {
    return `${this.name} won the ${this.sport} event!`;
  }
}

const athleteArray = [
  new Person({
    name: 'Mike',
    age: '33',
    sport: 'sitting',
    quote: 'Hello Super nintendo chalmers'
  }),

  new Person({
    name: 'Bill',
    age: '35',
    sport: 'cooking',
    quote: 'stop that'
  })
];

athleteArray.forEach(person => console.log(person.win()));

If you want to do it your way, you need to create a function. You just assign what it returns to the property

let athleteArray = [
  rupert = {
    name: 'Mike',
    age: '33',
    sport: 'sitting',
    quote: 'Hello Super nintendo chalmers'
  },

  alice = {
    name: 'Bill',
    age: '35',
    sport: 'cooking',
    quote: 'stop that'
  }
];


const win = function(name, sport) {
  console.log(`${name} won the ${sport} event!`)
}

//loop to add new 'win' property

for (let i = 0; i < athleteArray.length; i++) {
  athleteArray[i].win = () => win(athleteArray[i].name,
    athleteArray[i].sport)
  console.log(athleteArray[i])
  console.log(typeof athleteArray[i].win)
  athleteArray[i].win();
  
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to return something from the win function:

let athleteArray = [
  rupert = {
    name: 'Mike',
    age: '33',
    sport: 'sitting',
    quote: 'Hello Super nintendo chalmers'
  },

  alice = {
    name: 'Bill',
    age: '35',
    sport: 'cooking',
    quote: 'stop that'
  }
];


const win = function(name, sport) {
  return `${name} won the ${sport} event!`;
}

//loop to add new 'win' property

for (let i = 0; i < athleteArray.length; i++) {
  athleteArray[i].win = win(athleteArray[i].name,
    athleteArray[i].sport)
  console.log(athleteArray[i])
  console.log(typeof athleteArray[i].win )
}

about 4 years ago · Juan Pablo Isaza Relatório

0

The 'win' function does not return anything. The way you wrote the code, 'athleteArray[i].win' will be undefined. To do what you want, you should do something like that:

  athleteArray[i].win = () => win(athleteArray[i].name, athleteArray[i].sport)

It's easier to understand the error if the code were like that:

const returnedValue = win(athleteArray[i].name,  athleteArray[i].sport)

// Returned value is undefined
athleteArray[i].win = returnedValue
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