Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda