退出递归函数JavaScript

时间:2017-11-13 20:48:07

标签: javascript recursion

我有一些代码,我可以退出代码,但是返回的内容是未定义的,这是奇怪的,如果我console.log我想要返回它给出正确的值。这是我的代码:



function encryptPass(text, result) {
        var a = text.length -1;
        var c = text.charCodeAt(a);
        if      (65 <= c && c <=  90) result += String.fromCharCode((c - 65 + 4) % 26 + 65);  // Uppercase
        else if (97 <= c && c <= 122) result += String.fromCharCode((c - 97 + 4) % 26 + 97);  // Lowercase
        else                          result += text.char;  // Copy
        
        if (a == 0) {
            console.log(result);
            return result;
        } else {
          encryptPass(text.substr(0, a), result);
        }       
       return; 
    }
console.log('lemons '+ encryptPass('hello',''));
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你有两个问题:

    if (a == 0) {
        encrypted = result;
        return 'encrypted'; // you return the word encrypted instead of the variable results
    } else {
      encryptPass(text.substr(0, a), result);
    }      
    return; // you return undefined

<强>解决方案:

&#13;
&#13;
function encryptPass(text, result) {
  var a = text.length - 1;
  var c = text.charCodeAt(a);
  if (65 <= c && c <= 90) result += String.fromCharCode((c - 65 + 4) % 26 + 65); // Uppercase
  else if (97 <= c && c <= 122) result += String.fromCharCode((c - 97 + 4) % 26 + 97); // Lowercase
  else result += text.char; // Copy

  if (a == 0) {
    return result; // return the result
  }

  // you can skip the else check, since this is only option left
  return encryptPass(text.substr(0, a), result); // return the results of encryptPass
}
console.log('lemons ' + encryptPass('hello', ''));
&#13;
&#13;
&#13;