【问题标题】:Is it possible to use .contains() in a switch statement?是否可以在 switch 语句中使用 .contains() ?
【发布时间】:2014-09-10 16:12:39
【问题描述】:

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

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

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

解决方案:

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

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");
}

【问题讨论】:

  • 你试过用正则表达式吗?
  • 没有。它必须是switch(true) { case location.href.contains("google") ...,这很愚蠢
  • 是的,但它不会达到您的预期。用于切换的表达式被评估一次 - 在这种情况下,结果将是真/假,而不是字符串。
  • 你需要使用 contains ('Google') 并且 no if 在 switch 中不起作用。否则使用

标签: javascript switch-statement contains


【解决方案1】:

“是的”,但它不会达到您的预期。

用于开关的表达式被评估一次 - 在这种情况下,contains 评估结果为真/假(例如switch(true)switch(false)) , 不是一个 case 中可以匹配的字符串。

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

var loc = ..
if (loc.contains("google")) {
  ..
} else if (loc.contains("yahoo")) {
  ..
} else {
  ..
}

但是,请考虑是否有一个 classify 函数返回“google”或“yahoo”等,可能使用上述条件。然后它可以这样使用,但在这种情况下可能会过大。

switch (classify(loc)) {
   case "google": ..
   case "yahoo": ..
   ..
}

虽然上面讨论了 JavaScript 中的此类内容,但 Ruby 和 Scala(可能还有其他)提供了处理一些更“高级开关”用法的机制。

【讨论】:

  • 感谢您的回答。它帮助我找到了一个解决方案,我更新了包含的主要答案。
  • @Rayz321 是的,这也是一种可能的形式——但这不是我的偏好/推荐。
  • Contains 不是 javascript 中的方法,它的包含即 loc.includes("yahoo")
【解决方案2】:

另一种实现可能是这样。内容不多,但读起来比 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');
};

【讨论】:

  • 至少在答案部分=)
猜你喜欢
  • 1970-01-01
  • 2021-11-04
  • 2011-07-31
  • 2015-07-17
  • 1970-01-01
  • 2016-04-09
  • 2022-01-24
  • 2021-08-11
  • 1970-01-01
相关资源
最近更新 更多