我有一些代码,我可以退出代码,但是返回的任何内容都是未定义的,这很奇怪,如果我控制台.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',''));
您有 2 个问题:
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
溶液:
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', ''));