循环如何继续这样:
我的变量是这样的:
var array = [1,2,3,4,5,6,7,8,9,10]
var maximunNumbers = 6
var eachRound = 2
我想打印数字:
In round 1 : print array[0] and array[1]
In round 2 : print array[2] and array[3]
In round 3 : print array[4] and array[5]
In round 4 : print array[0] and array[1] //numbers repeat themselves from here
In round 5 : print array[2] and array[3]
and so on ...
答案 0 :(得分:1)
var array = [1,2,3,4,5,6,7,8,9,10];
var maximunNumbers = 6;
var eachRound = 2;
var i, k;
for( i = 0; i < 10; ++i ) {
var result = 'In round ' + i + ' : ';
for( k = 0; k < eachRound; ++k ) {
var array_index = ( ( i * eachRound ) + k ) % maximunNumbers;
result += ' array[' + array_index + '] = ' + array[array_index];
}
console.log( result );
}
在第0轮中:数组[0] = 1数组[1] = 2
在第1轮中:array [2] = 3 array [3] = 4
在第2轮中:array [4] = 5 array [5] = 6
在第3轮中:array [0] = 1 array [1] = 2
在第4轮中:array [2] = 3 array [3] = 4
在第5轮中:array [4] = 5 array [5] = 6
在第6轮中:array [0] = 1 array [1] = 2
在第7轮中:array [2] = 3 array [3] = 4
在第8轮中:array [4] = 5 array [5] = 6
在第9轮中:array [0] = 1 array [1] = 2
答案 1 :(得分:0)
一种方法是编写一个步长为2的内部计数器。
var array = [1,2,3,4,5,6,7,8,9,10];
var maximunNumbers = 6;
var eachRound = 2;
var intCount = 0;
for (i=0;i<10;i++){
print array[intCount] and array[intCount+1]
intCount=intCount+2
}
这将首次打印您的数组[0]和数组[1]。第二次,intCount将为2.因此它将打印数组[2]和数组[3]。
请注意“我”的重要程度。写得像这样,intCount将超出你的范围。