...

View Full Version : Inside loop only do something every forth time



code-in-time
05-31-2012, 06:19 PM
Hi


I have an array and want to insert "--" in between every 4th number - how do i do this?

Thanks



var arr = {1,2,3,4,5,6,7,8,9};

var n = "";

for (var i=1 ; i<= arr.length ; i ++){

n += arr[i].toString();

if( if the forth loop ){

n += "--"; //only add this every 4 loops

}

}

alert(n); //wanted result 1234--5678--9

Krupski
05-31-2012, 06:26 PM
var arr = [ 1,2,3,4,5,6,7,8,9 ];
var n = "";
for (var i = 0; i < arr.length; i++) {
n += arr[i];
if(((i + 1) % 4) == 0) {
n += "--"; //only add this every 4 loops
}
}
alert(n); //wanted result 1234--5678--9

code-in-time
05-31-2012, 06:45 PM
thanks

what does the % mean?

felgall
05-31-2012, 08:24 PM
% means remainder or modulo

1%4 = 1
2%4 = 2
3%4 = 4
4%4 = 0
5%4 = 1
6%4 = 2
7%4 = 3
8%4 = 0
9%4 = 1

and so on -so if you increment the nember on the left by one every time the result will be zero when that number is exactly divisible by 4 - ie every fourth time.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum