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

108
Visualizações
Further understanding of array.map

I'm currently learning JS and I'm not quite sure what this does. Could I please get some explanation?

  num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");

Thank you.

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

0

map calls a provided callbackFn function once for each element in an array, in order, and constructs a new array from the results. callbackFn is invoked only for indexes of the array which have assigned values (including undefined).

// Arrow function
map((element) => { ... })
map((element, index) => { ... })
map((element, index, array) => { ... })

// Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Inline callback function
map(function(element) { ... })
map(function(element, index) { ... })
map(function(element, index, array){ ... })
map(function(element, index, array) { ... }, thisArg)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

So with that in mind, let's take a look at the JS code

  num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");

For me this code is somewhat incomplete, but I would imagine that you might have something like

let num = [1,2,3,4,5,6,7,8,9,10]

num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");
// we reassign the value of num to a NEW array, because map will create that for us.
// when we call .map() on our array, it will begin to iterate over the array
// we're giving each element an arbitrary name of 'x'
// In our return statement, we are going to make a comparison with a ternary operator.
// We are going to loosely compare each element of the array (x) to zero.
// If this is true, we reassign x to 1. If this is false, we reassign to 0
// We then join the array with no separators using Array.prototype.join()
// => '0000000000'

So now if we do it with another array, let's see what happens.

let num = [0,0,1,1,4,0,5]
num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");
// => '1100010'
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