<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "";
for ( var i = 0; i < 5; i++ ) {
x = x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
我理解它返回的内容,但我不理解每个语句之前的 x。
x = x + "The number is " + i + "<br>";
最佳答案
x 是一个变量,它将在循环中增长。
行:
x = x + "The number is " + i + <br>
仅附加行 “数字是” + i + 行尾 到 x 的当前值。
将此行视为:
var y = x + "The number is " + i + <br>
x = y
在循环结束时,x 值得:
“数字是0
数字是1
数字是2
数字是3
数字是4
”
如果不是 x = "",而是 x = "Hello, ",那么最终结果将是:
“您好,号码是0
号码是1
号码是2
号码是3
号码是4
”
关于javascript - 为什么+"the number is"之前有x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14674327/