简体   繁体   中英

Return function returns nothing

I am using this function in js(it should return the special subject) :

function getSubjectByNumber(subject_number) {

  var subject_name;

  if (subject_number === 0) {
    return subject_name = "Deutsch";
  }
  if (subject_number === 1) {
    return subject_name = "Englisch";
  }
  if (subject_number === 2) {
    return subject_name = "Latein";
  }
  if (subject_number === 3) {
    return subject_name = "Kunst";
  }
  if (subject_number === 4) {
    return subject_name = "Musik";
  }
  if (subject_number === 5) {
    return subject_name = "Instrument/G. (Additum)";
  }
  if (subject_number === 6) {
    return subject_name = "Französisch (spät.)";
  }
  if (subject_number === 7) {
    return subject_name = "Theater und Film";
  }
  ..//That goes a long time...
}

And I call the return method with this code line:

var subject_name = getSubjectByNumber(subject);   

But as I see it returns nothing (''), because the var subject_name stays always empty. I hope anyone can help me. Thanks in advance.
~mb

Please consider an array.

A coercion is not even needed so just do the following - as you can see the 0 and "0" work the same

 function getSubjectByNumber(subject_number) { return ["Deutsch","Englisch","..."][subject_number] || "not found"; } console.log( 0, getSubjectByNumber(0), "0", getSubjectByNumber("0"), 1, getSubjectByNumber(1), 10, getSubjectByNumber(10) // not found ); 

You are using the strict equality operator ( === ), which doesn't do any type conversion on the operands. If subject is a String, then that would explain it because "0" === 0 is false . In this scenario, you need to either convert subject to a number (just prepending + to it would do it) or use == to do an equality with conversion check.

But, all your if/then logic as well as the string/number issue can be eliminated if you just use an array.

 let subjects = ["Deutsch", "Englisch", "Latein", "Kunst", "Musik", "Instrument/G. (Additum)", "Französisch (spät.)", "Theater und Film"]; function getSubjectByNumber(subject_number) { return subjects[subject_number]; } console.log(getSubjectByNumber(0)); console.log(getSubjectByNumber("0")); console.log(getSubjectByNumber(6)); console.log(getSubjectByNumber(7)); 

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