如何移动给定字符串中的每个字母N在字母表中放下?标点符号,空格和大小写应保持不变.例如,如果字符串是"ac"且num是2,则输出应为"ce".我的代码出了什么问题?它将字母转换为ASCII并添加给定的数字,然后从ASCII转换回字母.最后一行替换空格.
function CaesarCipher(str, num) {
str = str.toLowerCase();
var result = '';
var charcode = 0;
for (i = 0; i < str.length; i++) {
charcode = (str[i].charCodeAt()) + num;
result += (charcode).fromCharCode();
}
return result.replace(charcode.fromCharCode(), ' ');
}
Run Code Online (Sandbox Code Playgroud)
我越来越
TypeError: charcode.fromCharCode is not a function
Run Code Online (Sandbox Code Playgroud)
小智 9
您需要使用String对象将参数传递给fromCharCode方法.尝试:
function CaesarCipher(str, num) {
// you can comment this line
str = str.toLowerCase();
var result = '';
var charcode = 0;
for (var i = 0; i < str.length; i++) {
charcode = (str[i].charCodeAt()) + num;
result += String.fromCharCode(charcode);
}
return result;
}
console.log(CaesarCipher('test', 2));Run Code Online (Sandbox Code Playgroud)
我不得不修改return语句,因为它为我引入了一个bug