我似乎拥有我想做的事情所需的一切。但是,我似乎无法让它显示我想要的显示方式。
<!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 .
如果您有兴趣,我们将面临一些挑战。
- 使您的函数能够使用参数显示任何乘数的表格。
- 将表格放入实际的 HTML 表格元素中。
关于javascript - 打印 5 个乘法表(从 1 到 12),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33623437/