Yvo*_*von 2 javascript function switch-statement
我有一种情况switch
用来过滤掉一个大数组。它就像
var myArray = ['a','b','c','d'];
$.each( myArray, function (ind, elem) {
switch (true) {
case (elem === 'a'):
// do something to a
break;
case (elem === 'b'):
// do something to b (but not to a)
break;
always: // do this if we have done something
alert('we have done something!');
}
});
Run Code Online (Sandbox Code Playgroud)
因此,我希望为a
andb
但不是为c
or发出警报d
。
有没有办法实现这一目标?
首先,我会写得switch
更地道:
switch (elem) {
case 'a':
// 'a' code
break;
case 'b':
// 'b' code
break;
default:
// anything else
}
Run Code Online (Sandbox Code Playgroud)
请注意,这default
是您要查找的标签。另一方面,如果您只想在匹配时才做某事,那么 aswitch
可能不是最干净的方法,因为没有一种好的方法可以为每种情况包含样板代码(除了只是复制/粘贴) .
您可以使用单独的函数,并构造函数以设置标志:
var didSomething = false;
function doSomething(fn) {
fn();
didSomething = true;
}
switch (elem) {
case 'a':
doSomething(function() { /* 'a' code */ });
break;
case 'b':
doSomething(function() { /* 'b' code */ });
break;
}
if (didSomething) {
alert("did something");
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以制作地图:
var actions = {
'a': function() { /* 'a' code */ },
'b': function() { /* 'b' code */ }
};
if (actions[elem]) {
actions[elem]();
alert("did something");
}
Run Code Online (Sandbox Code Playgroud)