Javascript 请有人解释一下这个脚本
当我在浏览器中运行以下代码时Javascript 请有人解释一下这个脚本,javascript,html,dom,Javascript,Html,Dom,当我在浏览器中运行以下代码时 <!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>
<!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>
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
单击时,它会在“尝试”按钮下方显示以下内容。我的问题是这部分代码x=x+的数字是+i+;。当替换为x=时,数字为+i+;它只显示。有些人请解释为什么会这样。因为x是显示的字符串。在循环的每个增量处,当等号右侧的x保持不变时,所有旧的数字为+i+
也保持不变。删除等号右侧的x时,旧字符串将被覆盖,只显示较大的数字i。您需要的是一个闭包。在for循环中,尝试以下脚本 The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 4
(function(x, i){
x=x + "The number is " + i + "<br>";
})(x, i);
x+='数字是'+i+,通过一个好的javascript教程,您会得到更好的帮助。顺便问一下,这是家庭作业吗?