好的我试着学习JS,但是像这样的小东西让它很难让我想说只是忘了它
例如w3schools说A + = B与说A = A + B相同 但当我改变这个代码时,不使用A + = B操作数,并将其编码为A = A + B不起作用! 这意味着A + = B并不意味着与A = A + B相同!
heres w3chools示例即时学习“while”循环,而heres是我下面的问题,这是他们每次在新行上编写“数字是1-19”的代码,因为它应该
<h1>JavaScript while</h1>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
这里是MY Code Below和im basicall将它从“A + = B改写为A = A + B”并且它只在同一行写下“The Number is”ONE TIME和1-19号!
<h1>JavaScript while</h1>
<p id="demo"></p>
<script>
var text = "<br>The number is ";
var i = 0;
while (i < 10) {
text = text + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
答案 0 :(得分:1)
您的代码和W3S
之间的区别在于,每次都将i
值添加到文本而不是所需的文本,因此输出将为<br>The number is 123456789
以避免您应该每次都添加<br>The number is
:
var text = '',
text2 = ''
prefix = '<br>The number is',
i = 0;
console.clear();
while (i < 10) {
var toAppend = prefix + i
text += toAppend;
text2 = text2 + toAppend;
i++;
}
document.write(text);
document.write('<br />*****************************');
document.write(text2);
&#13;
答案 1 :(得分:0)
每次循环时都可以连接字符串:
var text = "";
var i = 0;
while (i < 10) {
var curtext = document
.getElementById("demo")
.innerHTML;
document
.getElementById("demo")
.innerHTML = curtext + "<br>The number is " + i;
i++;
}
&#13;
<div id="demo"></div>
&#13;