Get answer from callback

Asked

Viewed 128 times

0

How do I pick up/use the callback response here?

const arr = ["Lucas"];

function minhaCall(sobrenome, indice) {
    return indice + 1 + ") " + sobrenome + " de Carvalho";
}

arr.forEach(minhaCall)

For example, I can’t give a console.log(arr.forEach(minhaCall))

how I would use the return of this function?

  • I don’t know if I understand very well what you meant, but you can put the console.log in place of return.

  • Yes, Caique, but then it wouldn’t do me any good. For example, the.log console I can only use in the console context, but if I wanted to use this data elsewhere? I’m sorry if you’re a little confused.

  • 1

    It seems more like you want to make one map of array than a forEach.

  • Relax, I think I get it now, I believe forEach is not the best way for it, but first solution that came to mind would be to store/increment in a variable the returns.

  • 2

    You better say what you really want to do instead of imagining a solution and try to understand it. What you have to input and what to expect out?

2 answers

2


Apparently what you want is to generate a new array of strings from the original. If applicable, this is done with the Array.map, not the Array.forEach.

I recommend reading each documentation for more details:

So it would be:

const arr = ["Lucas"];

function minhaCall(sobrenome, indice) {
    return indice + 1 + ") " + sobrenome + " de Carvalho";
}

console.log(arr.map(minhaCall));

Or in a simplified way:

const arr = ["Lucas"];
const novoArr = arr.map((nome, i) => `${i+1}) ${nome} de Carvalho`);

console.log(novoArr);

-2

Your question is unclear, but I believe you’re trying to do something like this:

const arr = ['Lucas']

const minhaCall = (sobrenome, indice) => `${indice + 1}) ${sobrenome} de Carvalho`

arr.map((nome, i) => {
    console.log(minhaCall(nome, i))
})
  • 1

    Then the solution would be forEach same, not the map.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.