时间表JavaScript n00b

时间:2015-11-10 05:24:23

标签: javascript for-loop math

我似乎拥有我想要做的所有事情。但是,我似乎无法显示我希望它显示的方式。

<!DOCTYPE HTML>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <title>5 Times Table</title>
    <script type="text/javascript">
         /* Program to print the five times table from 1 to 12 in this format:
         5 x 1 = 5
         5 x 2 = 10
         5 x ...
         Input: There will be no user input, program will use a loop to create the 5 times table.
         Process: Define all the 5 times table between 1 and 12.
         Output: The 5 times table will be displayed.
         */
        function fiveTimesTable() {
            var result = 0;
            for (i=1; i<=12; i++){
                 result = "5 * " + i + result + i*5 + "<br>";
            var display =result;
            }
            document.getElementById("outputDiv").innerHTML = display;
            }       
</script>
</head>
<body>
    <h1>Five Times Table From 1 - 12.</h1>
    <h2>Press the button to display the table.</h2>
    <button type="button" onclick="fiveTimesTable()">Times Table</button>
    <div id="outputDiv"></div>
</body>
</html>
           ` 

2 个答案:

答案 0 :(得分:0)

你的代码很接近,但是如果把它分解成各个部分,它会更容易理解。

function fiveTimesTable() {
  var display = ""; // The table output HTML

  for (i = 1; i <= 12; i++) {
     var multiplier = 5;
     var result = i*5;

     display += multiplier+" * "+i+" = "+result+"<br>"; //Add each line to our output HTML
  }

  document.getElementById("outputDiv").innerHTML = display;
}

查看in this codepen

如果您有兴趣,可以继续提出一些挑战。

  1. 使您的功能能够使用参数显示任何乘数的表格。
  2. 将您的表放入实际的HTML表格元素中。

答案 1 :(得分:0)

<!DOCTYPE HTML>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <title>Tabla del 5</title>
    <script>`enter code here`
         /* Program to print the five times table from 1 to 12
         Input: The program will use a loop to create the 5 times table.
         Process: Write a defining  table and a program to display the five times tables
         Output: display the five times table from 1 to 12 in this format*/
        function FiveTimesTable() {
             var display = "";  
             for (i = 1; i <= 12; i++) {
                 var multiplier = 5;
                 var result = 5*i;
                 display += multiplier+" * "+i+" = "+result+"<br>"+"<br>";
             }  
        document.getElementById("outputDiv").innerHTML = display;
        }  
    </script>
</head>
<body>
    <h2>Five Times Table</h2>
    <h3>Press the button to display the 5 times table</h3>
    <button type="button" onclick="FiveTimesTable()">Times Table</button>
    <div id="outputDiv"></div>
</body>
</html>