2014-01-21 118 views
0

作業不是顯示數字25,75,125,175,而是要顯示在頁面上。我已經設置了if語句,但由於某種原因,我無法擺脫25,75,155號碼。請幫助!如何將數字替換爲字母

在此先感謝。

分配2

<script> 
    //start of Assignment 2-1 
    var new_text = ""; 
    var randMax = (Math.floor(Math.random() * 200)); 
    for (var i = 1; i < randMax; i++) { 
     new_text += i; 

     if (i == 25) { 

      new_text += "Twenty Five "; 

     } else if (i == 75) { 
      new_text += "Seventy Five "; 
     } else if (i == 125) { 
      new_text += "one hundred and twenty five ";; 
     } else if (i == 175) { 
      new_text += "one hundred and Seventy five "; 

     } else { 
      new_text += " "; 
     } 

    } 
    document.write(new_text); 


</script> 

回答

1

在的開始for循環,您可以使用new_text += i;。這意味着它會一直追加我到你的new_text字符串。如果你想使它有條件,你需要把它放在else語句中。

<script> 
     //start of Assignment 2-1 
     var new_text = ""; 
     var randMax = (Math.floor(Math.random() * 200)); 
     for (var i = 1; i < randMax; i++) { 


      if (i == 25) { 

       new_text = "Twenty Five "; 

      } else if (i == 75) { 
       new_text += "Seventy Five "; 
      } else if (i == 125) { 
       new_text += "one hundred and twenty five ";; 
      } else if (i == 175) { 
       new_text += "one hundred and Seventy five "; 

      } else { 
       new_text += i; 
       new_text += " "; 
      } 

     } 
     document.write(new_text); 


    </script> 
+0

這不起作用,new_text =「Twenty Five」;簡單地覆蓋所有的結果。要解決它移動「new_text + =我;」換成else語句。 –

+0

是的,我首先誤解了這個問題。一旦我意識到,我刪除了我的答案並進行了編輯。 – krikara

0
var new_text = ""; 
    var randMax = (Math.floor(Math.random() * 200)); 
    for (var i = 1; i < randMax; i++) { 

     if (i == 25) { 
      new_text += "Twenty Five "; 
     } else if (i == 75) { 
      new_text += "Seventy Five "; 
     } else if (i == 125) { 
      new_text += "one hundred and twenty five ";; 
     } else if (i == 175) { 
      new_text += "one hundred and Seventy five "; 

     } else { 
      new_text += i; 
     } 
     new_text += " "; 

    } 
    alert(new_text); 

移動 「NEW_TEXT + = i」 設置爲else塊。現在無論條件如何,它都會在每次迭代時運行