[英]JS Switch Case - Execute function for case block
Is it possible to execute a case block based on a function call/expression evaluation? 是否可以基于函数调用/表达式评估来执行案例块?
function decideRandomName(name) {
let n
switch (name) {
case name.toString().toUpperCase().startsWith("A"): // Is this possible?
console.log("here")
n = "Andshand"
break;
case name.toString().toUpperCase().startsWith("B"):
n = "Bandshand"
break;
default:
n = "Pandu saala"
}
return n;
}
When i execute this, it always executes the default block. 当我执行此操作时,它总是执行默认块。 If this kind of syntax is not supported then i believe js to throw me an error? 如果不支持这种语法,那么我相信js给我抛出错误? Can someone explain the concept here? 有人可以在这里解释这个概念吗?
Just switch for truthyness: 只需切换到真实性即可:
switch (true) { }
However in your case you could do: 但是,您可以这样做:
return {
"J": "Jonas",
"A": "Albert"
}[name[0].toUpperCase()] || "default";
Switch statements are used to evaluate different possible values of an expression. switch语句用于评估表达式的不同可能值。 They can be used where you might otherwise have a control flow structure like this: 它们可用于您可能具有如下控制流结构的地方:
if(someLetter === "A") {
// do whatever for "A"
} else if (someLetter === "B") {
// do whatever for "B"
} else if (someLetter === "C") {
// etc.,
// etc., and like so for D through Z
// etc.,
} else {
// default action
}
In your code, name
is (presumably) a string. 在您的代码中, name
(大概是一个字符串)。 But, according to MDN , .startsWith()
returns true or false. 但是, 根据MDN , .startsWith()
返回true或false。 So your cases are basically equivalent to case false:
and case false:
. 因此,您的案例基本上等于case false:
和case false:
And, since the value of name
is not false, you're not hitting those cases. 而且,由于name
的值不是false,因此您不会遇到这些情况。
I updated your code to demonstrate the intended usage of switch
. 我更新了您的代码以演示switch
的预期用法。
function decideRandomName(name) {
let n;
let firstLetter = name[0].toUpperCase();
switch (firstLetter) {
case "A":
console.log("here")
n = "Andshand"
break;
case "B":
n = "Bandshand"
break;
default:
n = "Pandu saala"
break;
}
return n;
}
The matching that occurs between the expression passed to switch, ( name
in this case) and each case expression is identical to the ===
algorithm. 传递给switch的表达式(在这种情况下为name
)与每种情况下的表达式之间的匹配与===
算法相同。
Since name
(a string
presumably) and name.toString().toUpperCase().startsWith("A")
(a boolean
value) can never be identical, none of the cases match and the default
block is executed. 由于name
(大概是一个string
)和name.toString().toUpperCase().startsWith("A")
(一个boolean
值)永远不能相同,因此没有任何一种情况匹配,并且default
块被执行。
As a work around you could do as @Jonas suggested and check for truthyness by: 作为一项工作,您可以按照@Jonas的建议进行操作,并通过以下方法检查真实性:
switch (true) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.