javascript:switch 语句中的常用命令

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)

因此,我希望为aandb但不是为cor发出警报d

有没有办法实现这一目标?

Poi*_*nty 5

首先,我会写得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)