Sidebar

0 votes

While iterating through a list of items, I would like to perform a certain task when an item is a multiple of a certain number. For example:

for (var i=0; i < lineCount; i++){

if(i == 33 || i == 66) {

addPage();

}

}

However, since the number of items in the list is unknown, I can't (and don't want to) include every multiple in my test (33, 66, 99, etc.). Is there a better way?

Thanks!

for (var i=0; i < lineCount; i++){

if(i == 33 || i == 66) {

addPage();

}

}

However, since the number of items in the list is unknown, I can't (and don't want to) include every multiple in my test (33, 66, 99, etc.). Is there a better way?

Thanks!

+1 vote

In JavaScript, you can use the "remainder" operator which uses a built-in modulo function in the JavaScript engine to give you the remainder of the division operation. The syntax is "var1 % var2", which will give you the remainder of var1 divided by var2.

So, to answer the posted question about lines that are multiples of 33, you would write:

for (var i = 0; i < lineCount; i++) {

if (i % 33 === 0) {

//this line is a multiple of 33, since the value stored in the variable "i", when divided by 33, gives us a remainder of 0

}

}

Modulus math can also be useful for things like finding odd or even rows, for the purpose of applying, say, a background color to every other row in an HTML table. NOTE: CSS3 allows for this to be handled directly with a CSS style, but that's another post.

Following the example of finding odd rows, you could code as follows:

for (var i = 0; i < data.length; i++) {

if (data[i] % 2 === 1) {

//odd row -> write out a tr with a background color

} else {

//even row -> write out a tr without a background color

}

}

Performing "% 2" is basically performing an odd/even test, telling you if the number being tested is a multiple of 2 or not.

The remainder operation can, of course, be performed using any number.

commented
Aug 7, 2017
by
marc-m-9513
(570 points)

This worked great, thanks again!

...