Js:无限循环遍历数组

时间:2017-10-21 19:20:02

标签: javascript arrays setinterval

短篇小说我想每隔4秒从一组图像中更改一个图像。我需要在这里添加什么来实现这一目标。

items()

3 个答案:

答案 0 :(得分:4)

您可以在索引上使用闭包。

function changeBackground() {
    var i = 0,
        imgURL = 'http://lorempixel.com/250/200/abstract/';
    return function () {
        document.getElementById('background').src = imgURL + list[i++];
        i %= list.length; // prevent looping over the length
    };
}

var list = [3, 1, 4, 7];

setInterval(changeBackground(), 4000);
//                          ^^         with brackets for returning function 
<img id="background">

答案 1 :(得分:0)

尝试:

var list = ["img1", "img2", "img3"];
var i=0;
function ChangeBackground () {
   i++;
   if(i>list.length-1){
       i=0;
   }
   document.getElementById('background').src = "images/"+list[i];
}

window.setInterval(ChangeBackground(), 4000);

请注意,这会污染命名空间。

答案 2 :(得分:0)

var list = ["img1", "img2", "img3"],
    i = 0;                                                            // declare and initialize i outside of the function

function ChangeBackground () {
    document.getElementById('background').src = "images/" + list[i];
    i = (i + 1) % list.length;                                        // increment i after each call to this function (make sure i come back to 0 if it exceeds the length of the array using the modulo % operator)
}

window.setInterval(ChangeBackground, 4000);                           // pass a reference to the function not its return value (notice there is no parens after the function name)