【问题标题】:run through a loop and then reset and run it again运行一个循环,然后重置并再次运行
【发布时间】:2012-08-14 01:18:20
【问题描述】:

我想将图像更改为图像“i”,直到图像用完,然后我想从头开始。

这是我需要做的

  • 运行以下代码直到 i >= n
  • 然后将 i 重置为零

代码:

  function advanceSlide()
  {
    i++;
    currentIMG ='"image"+i';
    changeBG(currentIMG);
  }

这是我到目前为止所拥有的,我只是在循环完成时休息 i 感到困惑:

  window.setInterval(function(){
    advanceSlide();
    }, 5000);

  function advanceSlide(){
    while (i<n){
      i++;
      currentIMG='"Image"+i';
      changeBG(currentIMG);
    }
  };

这涵盖了当i时我需要做什么,那么当i 不小于n时我该如何告诉它该做什么em>

【问题讨论】:

    标签: javascript loops increment


    【解决方案1】:

    使用全局imgIndex

    imgIndex = 0;
    noOfImages = 10;
    
    function advanceSlide(){
      imgIndex++;
      if( imgIndex >= noOfImages ) { imgIndex = 0; }
      currentIMG = "Image" + imgIndex;
      changeBG(currentIMG);
    }
    

    【讨论】:

      【解决方案2】:

      您不需要将advanceSlide 包装在函数中。您可以使用模数来重置 i

      window.setInterval(advanceSlide, 5000);
      function advanceSlide(){    
          i = (i+1)%n;
          currentIMG="Image"+i;
          changeBG(currentIMG);   
      }
      

      【讨论】:

      • 投了赞成票,因为这是最简洁的答案,即使其他人被接受了..现在我正在删除我的 cmets 所以不要混淆其他人将来找到这个 Q...对不起
      【解决方案3】:

      下次请把你的问题说清楚。

      int i = 0;
      while (true){
              i++;
              if (i<n){
                 currentIMG='"Image"+i';
                 changeBG(currentIMG);
              }
              else
              {
                 i = 0;
              }
      }
      

      【讨论】:

        【解决方案4】:

        当 i >= n 时,它会简单地退出循环并继续执行您在 while() { }

        之后放置的任何代码

        使用您设置的时间间隔,那里不需要闭包,因为它只调用另一个函数,可以简化为window.setInterval(advanceSlide, 5000);

        你也可以用 for 循环替换那个 while 循环,因为你只是增加一个索引

        window.setInterval(advanceSlide, 5000);
        
        function advanceSlide() {
            for(i = 0; i < n; i++) {
                // also here don't really need to store in a variable just pass straight in
                changeBG("Image" + i)
            }
        }
        

        对于这个答案,我假设您的 Interval 是您想要调用函数的方式...这里的另一个答案显示使用 while(1) 循环和内部的另一个循环,以便在没有计时器

        【讨论】:

          猜你喜欢
          • 2015-12-16
          • 1970-01-01
          • 1970-01-01
          • 2019-03-06
          • 1970-01-01
          • 1970-01-01
          • 2015-03-07
          • 2022-09-27
          • 2014-06-06
          相关资源
          最近更新 更多