我一直在为 FREECODECAMP 编写这段代码,但我一直在试图让答案正确出现,但我无法让代码在单词之间带有空格。它应该是凯撒密码,字母有 13 位移位。谁能看看我的代码并告诉我哪里出错了。
``
function rot13(str) {
let key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let ans = '';
let keyAlph = key.substring(13) + key.substring(0,13);
for(let i =0; i < str.length; i++){
let temp = str.charAt(i);
let index = key.indexOf(temp);
if(temp !== NaN){
ans += keyAlph.[index];
}
}
return ans;
}
``
要在结果中的单词之间添加空格,您可以检查当前字符是否为空格并将其添加到答案字符串中而不应用 rot13 转换,如下所示:
function rot13(str) {
let key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let ans = '';
let keyAlph = key.substring(13) + key.substring(0,13);
for(let i = 0; i < str.length; i++) {
let temp = str.charAt(i);
let index = key.indexOf(temp);
if(temp !== ' ') { // check if character is not a space
if(index !== -1) { // check if character is in the key
ans += keyAlph[index];
} else { // if character is not in the key, add it as is
ans += temp;
}
} else { // if character is a space, add it to the answer
ans += ' ';
}
}
return ans;
}