【问题标题】:CoderByte JavaScript Letter Changes - first stepsCoderByte JavaScript 字母更改 - 第一步
【发布时间】:2014-11-04 04:54:53
【问题描述】:

对于那些熟悉这个测验的人,我试图接受一个字符串参数并将每个字母转换为字母表中的字母。例如,参数“abc”应该变成“bcd”。

我的代码的第一部分有效。它采用参数的第一个字母并将其转换。现在我正在尝试对参数的每个字母执行此操作,然后将结果连接成一个字符串作为输出。这部分不起作用。我收到错误消息,“SyntaxError: Unexpected token ;”

function LetterChanges(str) { 
   var string = str.toLowerCase()
   var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",       
   "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
   var n = 0;
   var output = "";
   var currentLetter = string[n];
   var currentAlphaPos = alphabet.indexOf(currentLetter);
   var nextAlphaPos = currentAlphaPos + 1; 
   var nextAlpha = alphabet[nextAlphaPos];

   //the code above this works. The code below results in an error

  while (i = 1;i < string.length; i++){
      output += nextAlpha;
      n += 1;
   };

   return output;
}

我是初学者,所以提前谢谢。

【问题讨论】:

  • 您永远不会更新currentLettercurrentAlphaPosnextAlphaPosnextAlpha。这些值不会因为你改变了n而改变。

标签: javascript arrays counter


【解决方案1】:

您混淆了whilefor 循环。

你正在尝试做for (iterator; condition; step); while 语法就是 while (condition)

【讨论】:

  • 谢谢!疲倦的初学者眼睛在这里。它仍然不工作,但我更接近。它现在输出一堆相同的字母。 IE,[var n] 没有进展,我试图在 [for] 循环中这样做。
  • 更新:我想我明白了。我将一堆“全局 VAR”移入 [for] 循环。这似乎成功了。
  • 你没有任何全局变量;移动需要在每次迭代中更改的变量分配将解决您的问题,是的。
  • 风格提示:大写的函数名用于构造函数。 function letterChanges(str) {} 在这里更可取。
  • 感谢您的风格提示。有趣的是,[LetterChanges] 实际上是 CoderBytes 的内置代码。我也觉得很奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
  • 2016-05-09
  • 2013-08-04
  • 1970-01-01
  • 2022-11-04
  • 2011-09-29
相关资源
最近更新 更多