JavaScript 循环输出

JavaScript Loop Output

本文关键字:输出 循环 JavaScript      更新时间:2023-09-26

all.我是 JavaScript 的新手,所以希望这对你们来说是一个非常简单的问题。但我绝对,为了我的生活,不知道该怎么做!我正在创建一个时间表程序,我需要输出看起来像这样:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...

。等等。但是,每当它输出到屏幕时,它只显示循环的 LAST 输出。所以它将显示"5 x 12 = 60"。我需要它在每次程序通过循环时显示每个单独的输出。我将如何做到这一点?

提前非常感谢!

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
        <!-- 
        Input
            User clicks the "Compute Table" button.
        Processing
            The computer creates a times table based on the users' input.
        Output
            Outputs the table to the user.
        -->

<title>Times Table</title>
<script>
    function computeTable() {
    // Declaring some variables and pulling the integer from the HTML form. Nothing to see here.
    var integer = parseInt(document.getElementById('input').value);
    var i = 1;
    // Running the loop and doing all the arithmetic
    while (i < 12) {
        i++;
    }
    // This line displays the output to the user
    var output = document.getElementById('outputdiv');
    output.innerHTML = integer + " x " + i + " = " + (integer * i);
    }
</script>
</head>
<body>
<h1>Times Table</h1>
Please enter a positive integer: <input type="text" id="input">
<button type="button" onclick="computeTable()">Compute Table</button>
<hr>
<div id="outputdiv" style="font-weight:bold"></div>
</body>
</html>

每次变量递增时,您都需要更新div。

var output = document.getElementById('outputdiv');
while (i < 12) {
    output.innerHTML = integer + " x " + i + " = " + (integer * i);
    i++;
}        

虽然我认为它会很快更新您的结果,您可能无法看到每个结果。 也许你想要这样的东西?

var output = document.getElementById('outputdiv');
var html;
if (output.innerHTML.length != 0) {
    output.innerHTML = "";
}
while (i < 12) {
    html = output.innerHTML;
    html += (i > 1 ? ", " : "") + integer + " x " + i + " = " + (integer * i);
    output.innerHTML = html;
    i++;
}  

这应该给你带来类似result_1, result_2, result_3, //etc.

这是一个工作示例。 此外,正如Johnannes在他的回答和评论中指出的那样,更新内部HTML可以直接完成output.innerHTML += value;

这里有多个问题。

1)你只输出一次——所以无论你做什么,都只有一行。声音很合理,对吧?

2) 即使您多次输出,output.innerHTML = "..."也会覆盖任何以前的分配。'因为它是一个分配,它不会附加。

因此,解决方案在循环内挂起:

var i = 1;
while ( i < 12 ) {
    output.innerHTML += integer + " x " + i + " = " + (integer * i) + "<br>";
    i++;
}

这可以通过更短的方式完成,使用 for 循环:

for (var i = 1 ; i < 12 ; i++) {
    output.innerHTML += integer + " x " + i + " = " + (integer * i) + "<br>";    
}