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

158
Visualizações
how to conditionally define an array and avoid to have a null as element?

let's say we have the following code:

var numberofZeroArray = [10, 10, 10, 10, 10];

and I want to add another number between the second and third elements conditionally using a toggle

var addMore = XXX() // XXX() return true or false

so that when addMore is true then the add a number 5

[10, 10, 5, 10, 10, 10]

if false, keep the original list unchanged:

[10, 10, 10, 10, 10]

I tried

var addMore = true;
var numberofZeroArray = [10, 10, addMore ? 5 : null 10, 10, 10];  // is OK when addMore is true
// result is [10, 10, 5, 10, 10, 10]

it doesn't meet the expected result when addMore is false:

var addMore = false;
var numberofZeroArray = [10, 10, addMore ? 5 : null 10, 10, 10]; 
// result is [10, 10, null, 10, 10, 10]

I could use spread operator to define separate arrays for the first two elements and last three elements, but it is not feasible to do when the array contains a lot number of element. so what's the most easy way to achieve it?

about 4 years ago · Juan Pablo Isaza
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