2017-02-15 36 views
-1

我正在研究一個使用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; 
 
}

回答

1

i達到0線

var nextNumber = numbers[i - 1].charAt(0).toLowerCase() ... 

將是有問題的

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