我正在开发使用for
循环的Codewars挑战(此处:https://www.codewars.com/kata/ten-green-bottles)。我仍在编辑代码,但无论我改变多少,它都会继续说charAt
出错。我的代码在这里:
function tenGreenBottles(n) {
var numbers = [
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten"
];
var lyrics = "";
for (i = n - 1; i > -1; i--) {
var numberLine = numbers[i] + " green bottles hanging on the wall,\n";
var nextNumber = numbers[i - 1].charAt(0).toLowerCase() + numbers[i - 1].slice(1, numbers[i - 1].length);
if (i < 9) {
lyrics = lyrics + numberLine + numberLine + "And if one green bottle should accidentally fall,\n" + "There'll be " + nextNumber + " green bottles hanging on the wall.\n";
}
else {
lyrics = lyrics + "One green bottle hanging on the wall,\n" + "One green bottle hanging on the wall,\n" + "If that one green bottle should accidentally fall,\n" + "There'll be no green bottles hanging on the wall.";
}
}
return lyrics;
}
答案 0 :(得分:1)
当i
到达0行时
var nextNumber = numbers[i - 1].charAt(0).toLowerCase() ...
会有问题
答案 1 :(得分:0)
在循环的最后一次迭代中会出现.charAt()
错误。此时,i = 0
,numbers[i -1]
正在尝试访问数组位置-1的项目。这显然不存在,因此javascript认为它是“未定义的”,因此.charAt()
失败。
另外,你的测试(第18行):i < 9
,导致歌词开始,传统上保留为歌曲的最后一行,在函数参数的情况下n >= 10
,在任何其他情况下,它将被完全省略。
最后,如果有人为函数参数n输入大于10的值,你的函数将会失败。
建议:如下更改for循环。用于区分运行线和最终线的测试被更改为测试大于0的数字位置(最终数字位于位置0),并且文本构建内容被移动到控制语句内以确保它们不是在处理最终数字位置时运行。
for (i = n - 1; i > -1; i--)
{
if (i > 0)
{
// since i > 0, [i - 1] will always be >= 0.
var numberLine = numbers[i] + " green bottles hanging on the wall,\n";
var nextNumber = numbers[i - 1].charAt(0).toLowerCase() + numbers[i - 1].slice(1, numbers[i - 1].length);
lyrics = lyrics + numberLine + numberLine + "And if one green bottle should accidentally fall,\n" + "There'll be " + nextNumber + " green bottles hanging on the wall.\n";
}
else
{
// We only want this when i == 0, but from the limitation
// set on the for loop (i.e. i > -1)we can assume that
// i will never be < 0.
lyrics = lyrics +
"One green bottle hanging on the wall,\n" +
"One green bottle hanging on the wall,\n" +
"If that one green bottle should accidentally fall,\n" +
"There'll be no green bottles hanging on the wall.";
}
}
-S