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.
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]();
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();