Is it possible to use .contains() in a switch statement?(是否可以在 switch 语句中使用 .contains() ?)
问题描述
这只是我正在尝试做的一个简单示例:
This is just a simple example of what I'm trying to do:
switch (window.location.href.contains('')) {
case "google":
searchWithGoogle();
break;
case "yahoo":
searchWithYahoo();
break;
default:
console.log("no search engine found");
}
如果不可能/不可行,那么更好的选择是什么?
If it's not possible/feasible what would be a better alternative?
解决方案:
在阅读了一些回复后,我发现以下是一个简单的解决方案.
After reading some of the responses I found the following to be a simple solution.
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");
}
推荐答案
是的",但它不会像你期望的那样.
"Yes", but it won't do what you expect.
用于切换的表达式被评估一次 - 在这种情况下,contains
评估结果为真/假(例如 switch(true)
或 switch(false)
), 不是一个 case 中可以匹配的字符串.
The expression used for the switch is evaluated once - in this case contains
evaluates to true/false as the result (e.g. switch(true)
or switch(false)
)
, not a string that can be matched in a case.
因此,上述方法行不通.除非此模式更大/可扩展,否则只需使用简单的 if/else-if 语句.
As such, the above approach won't work. Unless this pattern is much larger/extensible, just use simple if/else-if statements.
var loc = ..
if (loc.contains("google")) {
..
} else if (loc.contains("yahoo")) {
..
} else {
..
}
但是,请考虑是否存在返回google"或yahoo"等的classify
函数,可能使用上述条件.然后它可以这样使用,但在这种情况下可能会过大.
However, consider if there was a classify
function that returned "google" or "yahoo", etc, perhaps using conditionals as above. Then it could be used as so, but is likely overkill in this case.
switch (classify(loc)) {
case "google": ..
case "yahoo": ..
..
}
<小时>
虽然上面讨论了 JavaScript 中的此类问题,但 Ruby 和 Scala(可能还有其他)提供了处理一些更高级开关"使用的机制.
While the above discusses such in JavaScript, Ruby and Scala (and likely others) provide mechanisms to handle some more "advanced switch" usage.
这篇关于是否可以在 switch 语句中使用 .contains() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 switch 语句中使用 .contains() ?


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01