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

314
Visualizações
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.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

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]();
over 4 years ago · Santiago Trujillo Relatório

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();
over 4 years ago · Santiago Trujillo 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