每次从新索引开始循环遍历javascript数组

时间:2011-03-01 20:54:05

标签: javascript jquery

我有一个像这样的javascript数组:

 array = [
  {"Command": "SetDuration","QuestionId": "2","NewDuration": "1"},
  {"Command": "SetDuration","QuestionId": "2","NewDuration": "1"},
  {"Command": "SetDuration","QuestionId": "7","NewDuration": "7"},
  {"Command": "SetDuration","QuestionId": "6","NewDuration": "7"}
 ]

我的任务是在一分钟内循环一次,每次都以递增的索引开始,这样在3分钟后我将从数组[4]开始 怎么做到这一点? 谢谢!

4 个答案:

答案 0 :(得分:1)

设置计时器时,可以从另一个函数内部执行,该函数可以将索引维护为局部变量。

function loopVerySlowly(array) {
  var index = 0;
  function doSomething() {
    //
    // do something with array[index] ...
    //
    index = (index + 1) % array.length; // increment for next time
  }

  return setInterval(doSomething, 1000 * 60);
}

var interval = loopVerySlowly(array);

答案 1 :(得分:1)

封闭的魔力:

function createDwindlingLooper(arr) {
    var n = 0;
    return function() {
        for (var i = n; i < arr.length; i++) {
            console.log(i); // do real stuff here
        }
        n += 1; 
    }
}

var looper = createDwindlingLooper(array);

您可以通过以下方式满足您的计时器要求:

setInterval(createDwindlingLooper(array), 1000 * 60);

每次n执行时,looper的值将增加1,从而达到预期的效果:

var looper = createDwindlingLooper(array);
looper(); // 0, 1, 2, 3
looper(); // 1, 2, 3
looper(); // 2, 3
looper(); // 3
looper(); // 

答案 2 :(得分:0)

这取决于您希望如何执行迭代。一种方法是调用settimeout四次以微小增量在不同的索引上运行,例如

for (var i=0 ; i<4 ; i++)
    settimeout(function(i){ return function(){
        // process here using i as index 
    }, 60000*i);

答案 3 :(得分:0)

var checkme = {
    init: function(start) {
        for (var i = start; i < array.length; i++) {
            // alert(array[i].Command + ":" + array[i].QuestionId);
            //do what you want here
        };
        // start a new loop from current end
        if (array.length < start) {
            var t = setTimeout(checkme.init(start+1), 60000);//delay one minute
        };
    }
};
var t = setTimeout(checkme.init(0), 60000);//start first one in 1 minute

为了让BIT更有趣,请在每条记录的当前(第一个)数组元素上使用“NewDuration”,这样您就可以通过数据改变时间延迟量:)

不是你要求的确切,但为什么不呢!

var checkme = {
    init: function(start) {
        for (var i = start; i < array.length; i++) {
            // alert(array[i].Command + ":" + array[i].QuestionId);
            //do what you want here
        };
        // start a new loop from current end
        var timedelay = array[start].NewDuration * 60000;
        // delay by NewDuration # minutes
        if (array.length < start) {
            var t = setTimeout(checkme.init(start+1), timedelay);
        };
    }
};
var t = setTimeout(checkme.init(0), 60000);//start first one in 1 minute