javascript - 打印 5 个乘法表(从 1 到 12)

标签 javascript html 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>
           ` 

最佳答案

您的代码很接近,但如果将其分解为多个部分,会更容易理解。

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 表格元素中。

关于javascript - 打印 5 个乘法表(从 1 到 12),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33623437/

相关文章:

jquery - Yii2 - 如何用下拉列表隐藏 block

jquery - 如何创建子子菜单?

javascript - 需要我的 jQuery 选项卡在事件且已经打开时不关闭

command-line - 在For循环中退出-Windows命令处理器(CMD.EXE)

javascript - 用于即时消息系统的 Firebase/NoSQL 模式

javascript - &lt;script type=text/javaScript> vs &lt;script type=module>

javascript - 如何递归地将空对象{​​}设置为null?

c - 如果没有 printf,For 循环将无法工作

javascript - 如果在迭代 javascript 循环时使用 "in"和 "="运算符有什么区别?

java - 如何将 Java 对象转换为 JSON 字符串?