Javascript 如何设置图像数组并逐个循环

Javascript 如何设置图像数组并逐个循环,javascript,arrays,loops,Javascript,Arrays,Loops,对于更有javascript经验的人来说,这可能是一项相当简单的任务。我希望有一个图像数组,然后循环显示每个图像,每个图像之间有一定的时间间隔 将图像存储在数组中:var anArray=[image1,image2,image](我可以通过将图像的src放入这样的数组来将图像放入数组吗?当我尝试将每个图像当作字符串处理时。) 创建一个循环以遍历数组中的每个图像,并淡入每个图像:for(var i=0;i //用于将图像存储为数组 var count=0; var timerid = setIn

对于更有javascript经验的人来说,这可能是一项相当简单的任务。我希望有一个图像数组,然后循环显示每个图像,每个图像之间有一定的时间间隔

  • 将图像存储在数组中:var anArray=[image1,image2,image](我可以通过将图像的src放入这样的数组来将图像放入数组吗?当我尝试将每个图像当作字符串处理时。)
  • 创建一个循环以遍历数组中的每个图像,并淡入每个图像:for(var i=0;i //用于将图像存储为数组

    var count=0;
    var timerid = setInterval(function()
    {
       //fade in image
       count++;
       if(count > length)clearInterval(timerId); 
    }, 1000);
    

    更好的选择是在image.onload上使用display:none标记将所有图像添加到DOM中,然后使用循环逐个淡入图像,

    另一个选择是使用闭包作为计数器。计数器最优雅地实现为闭包

    // Wrapping the code in a self envoking function prevents polluting the global namespace.
    (function() {
    
        // The images array.
        var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
    
        // The counter function using a closure.
        var add = (function() {
            // Setting the counter to the last image so it will start with the first image in the array.
            var counter = images.length - 1;
            return function() {
                // When the last image is shown reset the counter else increment the counter.
                if(counter === images.length - 1) {
                    counter = 0;
                } else {
                    counter+=1;
                }
                return counter;
            }
        })();
    
        // The function for changing the images.
        setInterval(
            function() {
                console.log(images[add()]);
            }
        , 1000);
    
    })();
    

    显示您当前的代码?感谢您的快速响应并将其分解如果我已经将html中的图像集display添加为none,那么循环在图像中会如何消失?for(var I=0;I)
    // Wrapping the code in a self envoking function prevents polluting the global namespace.
    (function() {
    
        // The images array.
        var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
    
        // The counter function using a closure.
        var add = (function() {
            // Setting the counter to the last image so it will start with the first image in the array.
            var counter = images.length - 1;
            return function() {
                // When the last image is shown reset the counter else increment the counter.
                if(counter === images.length - 1) {
                    counter = 0;
                } else {
                    counter+=1;
                }
                return counter;
            }
        })();
    
        // The function for changing the images.
        setInterval(
            function() {
                console.log(images[add()]);
            }
        , 1000);
    
    })();