我想在一个字符串类型数组上运行一个循环,这样如果数组包含1000个字而不是循环应该给出起始值200而不是中断,当循环再次运行时它应该给出之前200个值之后的值,它是如何可能的在JavaScript中?
答案 0 :(得分:1)
您可能希望查看slice
,它具有您想要的本机支持,支持开箱即用的索引越界处理:
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];
答案 1 :(得分:0)
for (i=0; i<200; i++)
{
do whatever
}
var b=i-1;
for (i=b; i<400; i++)
{
do whatever;
}
等
答案 2 :(得分:0)
定义公共变量保持循环的长度
//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;
答案 3 :(得分:0)
希望这有帮助
var counter = 0; // global variable
for ( i=counter;i<=1000; i++)
{
if ( i !== 0 )
{
if ((/^\d*$/.test(i/200)))
{
counter = i+1;
break;
}
}
}
答案 4 :(得分:0)
这是一个迭代部分数组的函数。最后一个参数应该是一个将为循环的每个元素调用的函数。
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;
}
以下是使用示例:
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);
});
显示器:
0: 1
1: 2
---
2: 3
3: 4
---
4: 5
答案 5 :(得分:0)
您可以有效地执行以下操作:
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;
}
}
}
};
然后多次调用它,如:
SA.iterate();
SA.iterate();
SA.iterate();