如何处理JavaScript while循环的结尾

时间:2018-10-19 00:24:28

标签: javascript

function myFunction() {
    var text = "";
    var i = 5;
    while (i > 0) {
        text += "<br>The number is " + i;
        i--;
    }
    text += "<br>The number is " + i;
    if(i==0){
    	i=5;
      text += "<br>The number is reset to " + i;
    }

    while (i > 0) {
        text += "<br>The number is " + i;
        i--;
    }
    text += "<br>The number is " + i;
    document.getElementById("demo").innerHTML = text;
}
<html>
<body>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
</body>
</html>

我希望数字递减为0,然后重设为其原始值,然后再次递减为零。如果我将其显式设置为5,则执行中会出现中断(显示重置为5),并且我必须添加另一个while循环。

是否可以仅使用一个while循环?有更好的方案吗?

4 个答案:

答案 0 :(得分:2)

使用布尔变量(例如oneIterationCompleted)来查看完整的迭代是否已完成。当i首次成为-1时,将其设置为true,然后将i重置为5:

function myFunction() {
    var oneIterationCompleted = false;
    var text = '';
    var i = 5;
    while (i > -1) {
        text += "<br>The number is " + i;
        i--;
        if (i === -1 && !oneIterationCompleted) {
            i = 5;
            oneIterationCompleted = true;
        }
    }
    document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

另一种选择是在将i % 6初始化为11时显示i而不是i,不需要其他测试:

function myFunction() {
  let text = '';
  for (let i = 11; i > -1; i--) {
    text += "<br>The number is " + (i % 6);
  }
  document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

答案 1 :(得分:0)

为什么不仅仅提取逻辑并创建外部<my-component>textNode here</my-component>

for-loop
var demo = document.getElementById("demo");
function loop() {
  var text = "", i = 5;
  while (i > 0) text += "<br>The number is " + i--;  
  text += "<br>The number is " + i;
  demo.innerHTML += text;  
}

function myFunction() {
  var times = 2;
  for (var i = 0; i < times; i++) {
    loop();
    if (i !== times - 1) demo.innerHTML += "<br>Start over";
  }
}

答案 2 :(得分:0)

Id做这样的事情:

    function myFunction() {
    var text = "";
    var i = 5;
    var count = 0;
      while ( i > 0 && count < 2 ) {
          text += "<br>The number is " + i;
          i--;
          if( i === 0){
              i = 5;
              if( count < 1 ){
                  text += "<br>The number is reset to " + i;
              }

              count++;
          }

        document.getElementById("demo").innerHTML = text;
    }
}

答案 3 :(得分:-2)

var continue = true ;

function loop(ivalue) {
    var i = ivalue;
    while (i>0) {
        text+= "code"
        i--;

    }
   if(continue) loop(ivalue)
}

<button onclick="loop()">Try it</button>
<button onclick="continue = false">Break</button>