这只是我要执行的操作的一个简单示例:
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.
用于开关的表达式一次被评估 -在这种情况下,包含的结果将被评估为true/false(例如, switch(true)或 switch(false)),而不是可以匹配的字符串.
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 { .. }但是,请考虑是否有一个 classify 函数返回了"google"或"yahoo"等信息,也许使用了上述条件.然后可以原样使用它,但在这种情况下可能会造成过大杀伤力.
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()?
发布评论