了解Java Script中的循环

时间:2016-08-11 13:40:37

标签: javascript arrays loops

这是我的代码,我不确定我是否使用了正确的循环,但这基本上是想做的。我正在尝试让数组中的每个src每隔一秒打印一次,但是当试图打印myPix数组中的第二项时,myPix [thisPic]变得未定义。我真的很乐意得到一些帮助。谢谢!

function nextPic() {
    count = -1;
    thisPic = 0;

    if (thisPic == count) {
        document.write("This shouldn't ever happen");
        return false;
    } else {
        count++;
        var myPix = new Array("images/slideshow/Jellyfish.jpg", "images/slideshow/Penguins.jpg", "images/slideshow/Lighthouse.jpg");
        slideTag = document.getElementsByTagName("img")[1];
        slideTag.src = myPix[thisPic];
        currPic = slideTag.src;
        document.write(myPix[thisPic] + "<br />");
        document.write(currPic);
    }

    return false;
}
setInterval(nextPic, 1000);

2 个答案:

答案 0 :(得分:0)

根据您的代码理解,我已经找到了您的问题

    var myPix = ["images/slideshow/Jellyfish.jpg", "images/slideshow/Penguins.jpg", "images/slideshow/Lighthouse.jpg"];
    counter=0;
interval = setInterval (nextPic, 1000);
    function nextPic(){
        if(counter >= myPix.length){
            document.write("This shouldn't ever happen");
            clearInterval(interval);
        }
        else{

            slideTag = document.getElementsByTagName("img")[1];
            slideTag.src = myPix[counter];
            currPic = slideTag.src;
            document.write(myPix[thisPic] + "<br />");
            document.write(currPic);
            counter++;
        }

    }

答案 1 :(得分:0)

代码不起作用,因为&#34;循环&#34;没有共享变量。每次迭代都应该在同一个数组和相同的迭代器上工作,在你的代码中,每次迭代都会创建新的数组和新的迭代器,所以每次迭代都做同样的事情。

要正确工作,每个循环迭代都必须:

  1. 从数组获取当前图像src(在循环外部声明一个变量)
  2. 将其设置为img元素
  3. 将当前变量更改为当前+ 1(当前变量延迟外循环)
  4. 如果我们当前的数据大小超过数组大小 - 结束( clearInterval )或将当前设置为0 - 那么将一次又一次地启动...

    &#13;
    &#13;
    Time.parse('01/01/2015 3:00pm')
    &#13;
    //array declaration should be outside of loop
    
    var myPix = new Array("https://www.gravatar.com/avatar/50fbdd1dcbe4763a33a0e212f6a632c8?s=32&d=identicon&r=PG&f=1", "https://www.gravatar.com/avatar/5be6299fb284071a9fd2cc2cc0b9090a?s=32&d=identicon&r=PG", "https://i.stack.imgur.com/mlB9c.jpg?s=48&g=1");
    
    var currentPic=0; //this is number of current picture
    
    function nextPic(){
              
            if (currentPic>= myPix.length){
              
              // here example how to stop:
              //clearInterval(interval);
              //return;
              
              //we loop it over again from begging
              currentPic=0;
    
            }
      
            //get img in page - image by currentPic
            slideTag = document.getElementsByTagName("img")[1];//second
            //set src on this slideTag from array
            slideTag.src = myPix[currentPic];
      
            currentPic++;
    
            
    }
    
    var interval=setInterval (nextPic, 1000);//save interval in variable to use it to stop
    &#13;
    &#13;
    &#13;

      

    我从stackoverflow中获取示例头像以显示工作示例:)