i want to run a开发者_如何学Go loop on a string type array, such that if array contains 1000 words than loop should give starting 200 values than break and when loop runs again than it should give values after previous 200 values, how it is possible in javascript?
You probably want to check out slice
that has pretty much native support for what you want, with support for index-out-of-bounds handling out of the box:
var arr = [0,1,2,3,4,5,6,7,8,9];
var a = arr.slice(0, 3); // a = [1,2,3];
var b = arr.slice(6); // b = [6,7,8,9];
var c = arr.slice(5,7); // [5,6];
var d = arr.slice(100,200); // d = [];
var e = arr.slice(0, 100); // e = [1,2,3,4,5,6,7,8,9];
Hope this helps
var counter = 0; // global variable
for ( i=counter;i<=1000; i++)
{
if ( i !== 0 )
{
if ((/^\d*$/.test(i/200)))
{
counter = i+1;
break;
}
}
}
Define public variable hold the length of thew loop
//the public variable outside the function scope
var counter = 0;
for (var x = counter ; x < counter + 200 ; x++)
{
//do you action
}
//after finishing each loop increase it with 200
counter = counter + 200 ;
//don't forget to reset the counter if it reached to the maximum length of the array
if ( counter >= 1000 )
counter = 0;
Here is a function that will iterate part of an array. The last argument should be a function that will be invoked for each element of the loop.
function iterateSome(array, offset, count, fn)
{
for( var i = offset, l = Math.min(offset + count, array.length); i < l; ++i )
{
fn(i, array[i], array);
}
return i;
}
Here is an example of use:
var array = [1, 2, 3, 4, 5];
var offset = 0;
var batch = 2;
offset = iterateSome(array, offset, batch, function(i, element, array)
{
console.log(i + ": " + element);
});
console.log("---");
offset = iterateSome(array, offset, batch, function(i, element, array)
{
console.log(i + ": " + element);
});
console.log("---");
offset = iterateSome(array, offset, batch, function(i, element, array)
{
console.log(i + ": " + element);
});
Displays:
0: 1
1: 2
---
2: 3
3: 4
---
4: 5
You can efficiently do something like :
var SA = {
cOuter : 0,
iterate : function() {
var cInner = 1;
for (var y=SA.cOuter*200; y < 1000; y++, cInner ++) {
console.log(y);
if (cInner === 200) {
SA.cOuter++;
break;
}
}
}
};
and then invoke it multiple time like:
SA.iterate();
SA.iterate();
SA.iterate();
for (i=0; i<200; i++)
{
do whatever
}
var b=i-1;
for (i=b; i<400; i++)
{
do whatever;
}
etc
精彩评论