-1

使用下面的代码,我得到了意想不到的结果:

function myFunction() {
    var text = "something";
    var i;
    for (i = 0; i < 5; i++) {
        text += "The number is " + i + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
}
<p>Click the button to loop through a block of code five times.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

结果是:

somethingThe number is 0
The number is 1
The number is 2
The number is 3
The number is 4

为什么我没有得到下面的结果?

somethingThe number is 0
somethingThe number is 1
somethingThe number is 2
somethingThe number is 3
somethingThe number is 4
4

1 回答 1

0

好吧,这很简单:您从每个步骤开始,"something"然后添加;"The number is " + i + "<br>"你不要再添加了"something"。要获得您描述的结果,您必须从""(empty string) 开始并添加"something" + "The number is " + i + "<br>"到您的循环中,非常简单:

function myFunction() {
    var text = "";
    for (var i = 0; i < 5; i++) {
        text += "something" + "The number is " + i + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
}
<p>Click the button to loop through a block of code five times.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

于 2019-05-20T06:32:13.297 回答