如何使用JavaScript声明switch语句。 很容易知道,当根据变量的值执行不同的代码时,它将为您节省大量时间。
var jsLang = 'jquery';
switch (jsLang) {
case 'jquery':
alert('jQuery Wins!');
break;
case 'prototype':
alert('prototype Wins!');
break;
case 'mootools':
alert('mootools Wins!');
break;
case 'dojo':
alert('dojo Wins!');
break;
default:
alert('Nobody Wins!');
}
//outputs "jQuery Wins!"
您也可以通过省略中断来匹配多个案例,例如:
var jsLang = 'prototype';
switch (jsLang) {
case 'jquery':
alert('jQuery sucks!');
break;
case 'prototype':
alert('prototype sucks!');
case 'mootools':
alert('mootools sucks!');
case 'dojo':
alert('dojo sucks!');
break;
default:
alert('Nobody sucks!');
}
//outputs "prototype sucks! mootools sucks! dojo sucks!"