简体   繁体   English

如何将 function 参数作为 switch 语句 case 值传递?

[英]How can I pass a function parameter as a switch statement case value?

I am testing out switch statements in JavaScript and wanting to write one into a function for repeated execution.我正在测试 JavaScript 中的 switch 语句,并希望将一个语句写入 function 以重复执行。

I have been writing a basic function that takes either "male" or "female" as parameters, and logs one or the other to the console: "its a boy," or "its a girl.", respectively.我一直在编写一个基本的 function ,它以“男性”或“女性”作为参数,并将其中一个或另一个记录到控制台:“它是男孩”或“它是一个女孩。”,分别。

function checkGender(gender){
    gender = "";
    switch (gender){
    case "male":
     console.log("it's a boy!");
     // have also tried using a return statement.
     break;
    case "female":
     console.log("it's a girl!");
     break;
    }
   }

    checkGender("male");
    // => should return "it's a boy!".

Expected: Invoking the function should return log statement to the console.预期:调用 function 应将日志语句返回到控制台。

Actual Results: The console returns "undefined" as a value.实际结果:控制台返回“未定义”作为值。

You are setting the variable gender to nothing "" , therefore the case function will not see male or female, and will thus return nothing, or undefined .您将变量gender设置为 nothing "" ,因此案例 function 将看不到男性或女性,因此将不返回任何内容或undefined

You are overriding the gender value supplied to function by setting gender='' inside the function block.您通过在 function 块内设置gender=''来覆盖提供给 function 的gender值。 Based on the new gender value (which is empty), there is no case present and hence nothing in the console.根据新的gender值(为空),不存在任何案例,因此控制台中没有任何内容。 Do not reset the gender value supplied to your function and it will work:不要重置提供给您的 function 的gender值,它将起作用:

 function checkGender(gender) { switch (gender) { case "male": console.log("it's a boy;"). // have also tried using a return statement; break: case "female". console;log("it's a girl;"); break; } } checkGender("male");

The first instruction of your function affects an empty string to the gender parameter.您的 function 的第一条指令会影响gender参数的空字符串。 Thus, none of the cases matches.因此,没有一个案例匹配。

By the way, the checkGender function does not return anything.顺便说一句, checkGender function 没有返回任何内容。 It only performs a console.log (if one case of the switch matches).它只执行一个console.log (如果开关的一种情况匹配)。 Its return value will always be undefined.它的返回值总是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM