使用shift()和push()来循环数组值与使用计数器变量,最好的方法是什么?

Jam*_*lly 4 javascript

我在一组动画帧中循环遍历一组图像.有7个图像,从1-7循环完成动画.我需要这个动画无限循环,但我想知道哪个是最好的方法:

通过修改数组循环

/* Pull image from start of array. */
var image = frames.shift();
/* Process image. */
...
/* Add image back to end of array. */
frames.push(image );
Run Code Online (Sandbox Code Playgroud)

循环使用计数器变量

/* Pull image by counter offset. */
var image = frames[counter];
/* Process image. */
...
/* Increment or reset counter value. */
counter + 1 === frames.length ? counter = 0 : counter = counter + 1;
Run Code Online (Sandbox Code Playgroud)

有没有理由我选择一个而不是另一个?或者,有更好的方法吗?

nbr*_*oks 5

修改数组比仅使用变量来跟踪数组中的位置会更昂贵.更好的方法是,如果你无限循环,似乎只是使用while循环(而不是使用for你重置计数器的循环):

var i = 0;
while (true) {
    doSomething to array[i];

    i = (i+1) % array.length;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你的目标确实是每当给定的间隔过去时动画无限期地进行,那么循环就不是理想的了.请setInterval改用.

var frames = ...; //your images
var i = 0;
function animate() {
    do something to frames[i];
    i = (i+1) % array.length;
}

setInterval(animate, time_between_runs);
Run Code Online (Sandbox Code Playgroud)

time_between_runs再次调用函数之前应该经过多长时间.