How to determine if a number is odd in JavaScript

后端 未结 27 1832
一向
一向 2020-11-27 10:05

Can anyone point me to some code to determine if a number in JavaScript is even or odd?

27条回答
  •  旧巷少年郎
    2020-11-27 10:43

    Do I have to make an array really large that has a lot of even numbers

    No. Use modulus (%). It gives you the remainder of the two numbers you are dividing.

    Ex. 2 % 2 = 0 because 2/2 = 1 with 0 remainder.
    
    Ex2. 3 % 2 = 1 because 3/2 = 1 with 1 remainder.
    
    Ex3. -7 % 2 = -1 because -7/2 = -3 with -1 remainder.
    

    This means if you mod any number x by 2, you get either 0 or 1 or -1. 0 would mean it's even. Anything else would mean it's odd.

提交回复
热议问题