【问题标题】:Javascript string argument is undefined, cannot access .length propertyJavascript 字符串参数未定义,无法访问 .length 属性
【发布时间】: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


【解决方案1】:

在您的第一个函数中,循环内的i 应该是iCount

var iCount = 0;
while(iCount < value) {
    decodedWords.push(decodeWord(stringArray[iCount]));
    iCount++;
}

decodeWord 函数抱怨 word 未定义,因为您通过未定义的索引 (i) 将 stringArray 的成员传递给它。如果您通过定义的索引 (iCount) 抓取项目,decodeWord 将收到定义的 word 并能够抓取它的长度。

当然,您可能还希望rot13 返回输入字符串的编码版本,而不是“Confused!”的编码版本:

return decodedWords.join(" ");

【讨论】:

  • 天哪。我很尴尬哈哈。在遇到一些错误并进行故障排除并忘记更改 while 循环中的计数变量之后,我开始弄乱代码,因此当我修复其他错误时,我完全忽略了这个错误。对此感到抱歉,感谢您帮助我。听起来我编码太久了,需要休息一下……哈哈
  • 没必要,那些东西一直溜走!
【解决方案2】:

据我了解,您在这方面犯了一个错误 decodedWords.push(decodeWord(stringArray[i]));

改成

decodedWords.push(decodeWord(stringArray[iCount]));

希望它有效。有任何问题请告诉我

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 2021-05-17
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多