Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/421.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 请有人解释一下这个脚本_Javascript_Html_Dom - Fatal编程技术网

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教程,您会得到更好的帮助。顺便问一下,这是家庭作业吗?