-1

I have a function that I want to run every time my counter is 1, 3, 5 or 7. I am confused about what the right syntax is for jQuery in this situation.

My try so far:

if (i == (0, 2, 4, 6)) {

This is one of the many versions that I have tried, and failed with.

What is the right syntax, both for every odd number, as well as a specific collection of numbers, for example '3, 12, 512, 2231'?

halfer
  • 18,701
  • 13
  • 79
  • 158
Nenn
  • 347
  • 1
  • 3
  • 19
  • This has nothing to do with jQuery. It's a question about basic JavaScript comparisons. I suggest working through some basic JavaScript tutorials. – T.J. Crowder May 25 '16 at 10:06

3 Answers3

2

use the modulus operator in which the value %2 will either give a 0 or a 1 depending on the value:

if (i % 2 == 1) { // code for odd event

or do it for evens:

 if (i % 2 == 0) { // code for even event

What this does is divide the value by the number given (in this case 2) and returns the remainder. So if i is 5, dividing it by two will leave a remainder of 1, so its n odd number. If i = 44, dividing by two will leave a remainder of 0, so its even.

gavgrif
  • 13,077
  • 2
  • 17
  • 22
1
if(i % 2 == 1) //odd number

It's a modulo operator. See this documentation for more information on JavaScript arithmetic operators.

Explained in this thread.

Community
  • 1
  • 1
J.C. Fong
  • 389
  • 3
  • 13
0
if(i % 2) {
  // If Odd then do this
}

Is this not what you're after?

i % 2 will return 1 when an odd number and 0 when an even number.

Kershrew
  • 181
  • 9