首页 > 解决方案 > 如何在函数中插入while循环

问题描述

我正在尝试在名为 myFunction 的函数中插入一个 while 循环。当您单击按钮时,它应该显示数组结果。

<!DOCTYPE html>
<html>
<body>
<button id="btn">Click Me!</button>

<p id="i"><strong>this</strong> represents:</p>

<p id="demo"></p>
<script>

  function myFunction () {
let i = 0;
while(i<5){
    document.write(i  + '<br/>');
    i++;
}
}

var btn = document.getElementById("btn");
btn.addEventListener("click", myFunction());


</script>
</body>
</html>

标签: javascriptarrayswhile-loop

解决方案


您在 myFunction 之后缺少 ():

  function myFunction() {
let i = 0;
while(i<5){
    document.write(i  + '<br/>');
    i++;
}
} 

你确定要使用document.write而不是console.log(i)


推荐阅读