Find if variable is divisible by 2

2020-02-02 06:08发布

How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.

12条回答
太酷不给撩
2楼-- · 2020-02-02 06:50

You don't need jQuery. Just use JavaScript's Modulo operator.

查看更多
爷、活的狠高调
3楼-- · 2020-02-02 06:51

Hope this helps.

let number = 7;

if(number%2 == 0){      

  //do something;
  console.log('number is Even');  

}else{

  //do otherwise;
  console.log('number is Odd');

}

Here is a complete function that will log to the console the parity of your input.

const checkNumber = (x) => {
  if(number%2 == 0){      

    //do something;
    console.log('number is Even');  

  }else{

    //do otherwise;
    console.log('number is Odd');

  }
}
查看更多
迷人小祖宗
4楼-- · 2020-02-02 06:54

Use modulus:

// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0  
查看更多
淡お忘
5楼-- · 2020-02-02 06:58

You can do it in a better way (up to 50 % faster than modulo operator):

odd: x & 1 even: !(x & 1)

Reference: High Performance JavaScript, 8. ->Bitwise Operators

查看更多
可以哭但决不认输i
6楼-- · 2020-02-02 06:59

You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.

var x = 2;
if (x % 2 == 0)
{
  alert('even');
}
else
{
  alert('odd')
}
查看更多
乱世女痞
7楼-- · 2020-02-02 07:00
if (x & 1)
 itIsOddNumber();
else
 itIsEvenNumber();
查看更多
登录 后发表回答