【发布时间】:2018-04-27 21:18:43
【问题描述】:
所以我正在处理需要解码凯撒密码的 freecodecamp 挑战。我创建了一个从主函数调用的辅助函数来解码字符串中的每个单词。我在该辅助代码中遇到问题,因为它不断给我错误,即设置为参数的字符串参数未定义并且我无法访问长度。有人可以说明发生了什么吗?
免责声明:我是编码新手,过去 30 分钟都在寻找这个问题的答案,但我找不到。我觉得这个修复应该简单易行,如果有人觉得这个问题多余,请提前道歉。
代码如下:
function rot13(str) { // LBH QVQ VG!
var stringArray = [];
stringArray = str.split(" ");
var value = stringArray.length;
var decodedWords = [];
var iCount = 0;
while(iCount < value){
decodedWords.push(decodeWord(stringArray[i]));
iCount++;
}
return decodeWord("Confused!");
}
function decodeWord(word) {
var decodedWord = "";
for (i = 0; i < word.length; i++){
var cipherVal = word.charCodeAt(i);
var decodedVal = cipherVal;
if( cipherVal >= 97 && cipherVal <= 109 || cipherVal >= 65 && cipherVal <= 77){
decodedVal = cipherVal + 13;
}
else if(cipherVal >= 110 && cipherVal <= 122 || cipherVal >= 78 &&
cipherVal <= 90){
decodedVal = cipherVal - 13;
}
decodedWord += String.fromCharCode(decodedVal);
}
return decodedWord;
}
感谢您的建议!非常感谢。
【问题讨论】:
-
stringArray[i]i来自哪里? -
console.log(word),你会看到它是未定义的。需要将i更改为iCount(反之亦然),如何在stringArray中提供一些项目?
标签: javascript string methods parameters