简体   繁体   中英

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.

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 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.

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 .

You are overriding the gender value supplied to function by setting gender='' inside the function block. Based on the new gender value (which is empty), there is no case present and hence nothing in the console. Do not reset the gender value supplied to your function and it will work:

 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. Thus, none of the cases matches.

By the way, the checkGender function does not return anything. It only performs a console.log (if one case of the switch matches). Its return value will always be undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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