运行 ❯
获取您
自己的
网站
×
更改方向
保存代码
更改主题,深色/浅色
前往 Spaces
<!DOCTYPE html> <html> <body> <h2>JavaScript Function Closures</h2> <p>Counting with a local variable.</p> <p id="demo"></p> <script> // Initiate counter let counter = 0; // Function to increment counter function add() { let counter = 0; counter += 1; } // Call add() 3 times add(); add(); add(); // The result is not 3 because you mix up the globaland local counter document.getElementById("demo").innerHTML = "The counter is: " + counter; </script> </body> </html>