是否可以在switch语句中使用.contains()?

Ray*_*ayB 18 javascript contains switch-statement

这只是我正在尝试做的一个简单示例:

switch (window.location.href.contains('')) {
    case "google":
        searchWithGoogle();
        break;
    case "yahoo":
        searchWithYahoo();
        break;
    default:
        console.log("no search engine found");
}
Run Code Online (Sandbox Code Playgroud)

如果不可能/可行什么是更好的选择?

解:

在阅读了一些回复之后,我发现以下内容是一个简单的解决方案.

function winLocation(term) {
    return window.location.href.contains(term);
}
switch (true) {
    case winLocation("google"):
        searchWithGoogle();
        break;
    case winLocation("yahoo"):
        searchWithYahoo();
        break;
    default:
        console.log("no search engine found");
}
Run Code Online (Sandbox Code Playgroud)

use*_*740 14

"是的",但它不会做你期望的.

用于开关的表达式被计算一次 - 在这种情况下contains,结果为(例如switch(true)switch(false))计算结果为true/false ,而不是在案例中可以匹配的字符串.

因此,上述方法不起作用.除非这个模式更大/可扩展,否则只需使用简单的if/else-if语句.

var loc = ..
if (loc.contains("google")) {
  ..
} else if (loc.contains("yahoo")) {
  ..
} else {
  ..
}
Run Code Online (Sandbox Code Playgroud)

但是,请考虑是否存在classify返回"google"或"yahoo"等的函数,可能使用上述条件.然后它可以这样使用,但在这种情况下可能有点过分.

switch (classify(loc)) {
   case "google": ..
   case "yahoo": ..
   ..
}
Run Code Online (Sandbox Code Playgroud)

虽然上面在JavaScript中讨论过这种情况,但Ruby和Scala(以及其他可能的其他人)提供了处理更多"高级切换"用法的机制.

  • Contains 不是 javascript 中的方法,它包含 loc.includes("yahoo") (3认同)

Tim*_*imT 11

另一种实现可能是这样。内容不多,但读起来比 switch(true) 好...

const href = window.location.href;
const findTerm = (term) => {
  if (href.includes(term)){
    return href;
  }
};

switch (href) {
  case findTerm('google'):
      searchWithGoogle();
      break;
  case findTerm('yahoo'):
      searchWithYahoo();
      break;
  default:
      console.log('No search engine found');
};
Run Code Online (Sandbox Code Playgroud)