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

223
Vistas
JS Is it possible to use switch case in all values of an array automatically?

I want to to use a switch case to an array that has an uncertain number of elements, so there must to be a case to each value of this array; something like this:

let cities = ["City A", "City B", "City C"];

switch (cities){
    case cities[0]: //Action
    break;
    case cities[1]: //Action
    break;
    case cities[2]: //Action
    break;
}

But it cannot be written manually, it has to work like a "for"; something like this:

switch (cities){
    for(let i = 0; i < cities.length; i++){
         case cities[i]: //Action
         break;
    }
}

But JavaScript doesn't allow me to do this.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Need more context, but if I understand you correctly there is classical way to handle cases like this.

It is better to create mapping.

const map = {
  "City A": () => { // action }, 
  "City B": () => { // action }, 
  "City C": () => { // action }
};

const city = 'City A';
map[city]();
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can not define that, and also if you could, what would you put inside that switch case? If you can generalize it, you don't need switch case, if each action is specific for each item, then you can't use for. What you can do, is to store the action as a member of the map and call it based on the data:

const map = {
  "City A": {
      action: () => { // action specific to City A }
  } 
  "City B": {
      action: () => { // action specific to City B }
  }, 
  "City C": {
      action: () => { // action specific to City C }
  } 
};

Then you would be able to call it dynamically:

map['City A'].action();
about 4 years ago · Juan Pablo Isaza Denunciar
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