为什么此函数返回未定义?结果显然具有非null值,并且该调用正在输入第一个if语句,因为它打印了所需的输出。



function Swap(str, result) {
    if (str == "") {
      console.log(result);
      return result;
    }
    else if (str[0] == str.toUpperCase().substring(0,1)) {
      var newResult = result + str.toLowerCase().substring(0,1);
      Swap(str.replace(str[0], ""), newResult);
    }
    else {
      var newResult = result + str.toUpperCase().substring(0,1);
      Swap(str.replace(str[0], ""), newResult);
    }
   }

console.log(Swap("HelloW",""));

最佳答案

调用Swap("HelloW", "")将进入第二个if大小写(str以大写字母开头),它将调用Swap("elloW", "h")并且不返回任何内容。在其他两个分支上也需要return,而不仅仅是在第一个分支上。

关于javascript - 为什么此代码返回未定义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34303545/

10-11 22:31
查看更多