i want to run a 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?
A:
for(i=0;i<200;i++)
{ do whatever
}
var b=i-1;
for(i=b;i<400;i++)
{
do whatever;
}
etc
Rohan
2010-02-17 11:23:34
A:
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;
Amgad Fahmi
2010-02-17 11:28:35
A:
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;
}
}
}
rahul
2010-02-17 11:34:57
+1
A:
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];
David Hedlund
2010-02-17 11:41:45
A:
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
Vincent Robert
2010-02-17 14:00:51