Sentencia Switch múltiples casos en JavaScript
Necesito varios casos en la instrucción switch en JavaScript, algo así como:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
¿Cómo puedo hacer eso? Si no hay manera de hacer algo así en JavaScript, quiero saber una solución alternativa que también siga DRY concept.
16 answers
Utilice la función de transición de la instrucción switch
. Un caso coincidente se ejecutará hasta que se encuentre un break
(o el final de la instrucción switch
), por lo que podría escribirlo como:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-28 16:05:19
Esto funciona en JavaScript regular
function theTest(val) {
var answer = "";
switch( val ) {
case 1: case 2: case 3:
answer = "Low";
break;
case 4: case 5: case 6:
answer = "Mid";
break;
case 7: case 8: case 9:
answer = "High";
break;
default:
answer = "Massive or Tiny?";
}
return answer;
}
theTest(9);
Saludos.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-17 02:15:47
Aquí hay un enfoque diferente evitando la declaración switch
por completo:
var cases = {
afshin: function() { alert('hey'); },
_default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;
cases[ varName ] ? cases[ varName ]() : cases._default();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-03 10:03:09
En Js para asignar múltiples casos en switch Tenemos que definir different case without break
como se indica a continuación:
<script type="text/javascript">
function checkHere(varName){
switch (varName)
{
case "saeed":
case "larry":
case "afshin":
alert('Hey');
break;
case "ss":
alert('ss');
break;
default:
alert('Default case');
break;
}
}
</script>
Por favor vea el ejemplo haga clic en enlace
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-03 09:53:39
Si estás usando ES6, puedes hacer esto:
if (['afshin', 'saeed', 'larry'].includes(varName)) {
alert('Hey');
} else {
alert('Default case');
}
O para versiones anteriores de JavaScript, puede hacer esto:
if (['afshin', 'saeed', 'larry'].indexOf(varName) !== -1) {
alert('Hey');
} else {
alert('Default case');
}
Tenga en cuenta que esto no funcionará en los navegadores IE más antiguos, pero podría arreglar las cosas con bastante facilidad. Consulte la pregunta determinar si la cadena está en la lista en javascript para obtener más información.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:34
Puede usar el operador ' in'...
se basa en la invocación de objeto/hash...
así que es tan rápido como javascript puede ser...
// assuming you have defined functions f(), g(a) and h(a,b)
// somewhere in your code
// you can define them inside the object but...
// the code becomes hard to read, I prefer this way
o = { f1:f, f2:g, f3:h };
// if you use "STATIC" code can do:
o['f3']( p1, p2 )
// if your code is someway "DYNAMIC", to prevent false invocations
// m brings the function/method to be invoked (f1, f2, f3)
// and you can rely on arguments[] to solve any parameter problems
if ( m in o ) o[m]()
Disfruta, ZEE
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-06 12:51:28
Añadiendo y aclarando la respuesta de Stefano, puede usar expresiones para establecer dinámicamente los valores para las condiciones en switch, por ejemplo:
var i = 3
switch (i) {
case ((i>=0 && i<=5)?i:-1): console.log('0-5'); break;
case 6: console.log('6');
}
Así que en tu problema, podrías hacer algo como:
var varName = "afshin"
switch (varName) {
case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
console.log("hey");
break;
default:
console.log('Default case');
}
Aunque no sea tan SECO..
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-06 15:10:05
En el nodo parece que se le permite hacer esto:
data = "10";
switch(data){
case "1": case "2": case "3": //put multiple cases on the same line to save vertical space.
console.log("small"); break;
case "10": case "11": case "12":
console.log("large"); break;
default:
console.log("strange");
break;
}
Esto hace que el código sea mucho más compacto en algunos casos.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-01 09:12:30
Depende. Switch evalúa una vez y solo una vez. Después de un partido, todas las declaraciones de caso posteriores hasta 'romper' el fuego sin importar lo que diga el caso.
var onlyMen = true;
var onlyWomen = false;
var onlyAdults = false;
(function(){
switch (true){
case onlyMen:
console.log ('onlymen');
case onlyWomen:
console.log ('onlyWomen');
case onlyAdults:
console.log ('onlyAdults');
break;
default:
console.log('default');
}
})(); // returns onlymen onlywomen onlyadults
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-10 19:55:44
switch (myVariable)
{
case "A":
case "B":
case "C":
// Do something
break;
case "D":
case "E":
// Do something else
break;
default:
// Default case
break;
}
En este ejemplo, si el valor de myVariable es A, B, o C, ejecutará el código bajo el caso "C":.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-10 07:21:12
Puedo ver que hay muchas buenas respuestas aquí, pero ¿qué pasa si tenemos que comprobar más de 10 cases
? aquí está mi enfoque.
function isAccessible(varName){
let accessDenied = ['Liam','Noah','William','James','Logan','Benjamin',
'Mason','Elijah','Oliver','Jacob','Daniel','Lucas'];
switch (varName) {
case (accessDenied.includes(varName)?varName:null):
return 'Access Denied!';
default:
return 'Access Allowed.';
}
}
console.log(isAccessible('Liam'));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-23 15:30:07
Otra forma de hacer múltiples casos en la instrucción switch, cuando está dentro de una función
function name(varName){
switch (varName) {
case 'afshin':
case 'saeed':
case 'larry':
return 'Hey';
default:
return 'Default case';
}
}
console.log(name('afshin')); //Hey
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-09 22:37:46
Yo uso así:
switch (sensor){
case /Pressure/g.test(sensor):{
console.log('Its pressure!');
break;
}
case /Temperature/g.test(sensor):{
console.log('Its temperature!');
break;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-21 12:40:49
Podrías escribirlo así:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-11 15:28:20
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example1</title>
<link rel="stylesheet" href="css/style.css" >
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
function display_case(){
var num = document.getElementById('number').value;
switch(num){
case (num = "1"):
document.getElementById("result").innerHTML = "You select day Sunday";
break;
case (num = "2"):
document.getElementById("result").innerHTML = "You select day Monday";
break;
case (num = "3"):
document.getElementById("result").innerHTML = "You select day Tuesday";
break;
case (num = "4"):
document.getElementById("result").innerHTML = "You select day Wednesday";
break;
case (num = "5"):
document.getElementById("result").innerHTML = "You select day Thusday";
break;
case (num = "6"):
document.getElementById("result").innerHTML = "You select day Friday";
break;
case (num = "7"):
document.getElementById("result").innerHTML = "You select day Saturday";
break;
default:
document.getElementById("result").innerHTML = "You select day Invalid Weekday";
break
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Switch Case Example </h2>
<p>Enter a Number Between 1 to 7</p>
<input type="text" id="number" />
<button onclick="display_case();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-05 09:07:09
Simplemente cambie la condición del interruptor aprroach
switch (true) {
case (function(){ return true; })():
alert('true');
break;
case (function(){ return false; })():
alert('false');
break;
default:
alert('default');
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-16 10:02:56