查找变量是否可被2整除

时间:2010-05-12 16:59:20

标签: javascript modulo divide

如何判断变量是否可被2整除?此外,如果不是,我需要做一个功能,如果不是,我需要做一个不同的功能。

12 个答案:

答案 0 :(得分:271)

使用模数:

// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0  

答案 1 :(得分:27)

说真的,奇怪/偶数检查没有jQuery插件吗?

好了,不再了 - 在麻省理工学院的许可证下发布“Oven”jQuery插件来测试给定的数字是否为奇数/偶数。

http://jsfiddle.net/7HQNG/

也提供了源代码

测试套件位于http://jsfiddle.net/zeuRV/

(function() {
    /*
     * isEven(n)
     * @args number n
     * @return boolean returns whether the given number is even
     */
    jQuery.isEven = function(number) {
        return number % 2 == 0;
    };

    /* isOdd(n)
     * @args number n
     * @return boolean returns whether the given number is odd
     */
    jQuery.isOdd = function(number) {
        return !jQuery.isEven(number);
    };
})();​

答案 2 :(得分:13)

你不需要jQuery。只需使用JavaScript's Modulo运算符。

答案 3 :(得分:10)

您可以像这样使用模数运算符,不需要jQuery。只需用您的代码替换alerts

var x = 2;
if (x % 2 == 0)
{
  alert('even');
}
else
{
  alert('odd')
}

答案 4 :(得分:9)

你可以用更好的方式做到这一点(比模数运算符快50%):

奇数:x& 1 甚至:!(x& 1)

参考:高性能JavaScript,8。 - >按位运算符

答案 5 :(得分:7)

你也可以:

if (x & 1)
 itsOdd();
else
 itsEven();

答案 6 :(得分:3)

var x = 2;
x % 2 ? oddFunction() : evenFunction();

答案 7 :(得分:3)

if (x & 1)
 itIsOddNumber();
else
 itIsEvenNumber();

答案 8 :(得分:0)

请在您的控制台中编写以下代码:

var isEven = function(deep) {

  if (deep % 2 === 0) {
        return true;  
    }
    else {
        return false;    
    }
};
isEven(44);

请注意:如果输入的数字为偶数,则返回true。

答案 9 :(得分:0)

使用模数,但..以上接受的答案稍微不准确。我相信因为x是JavaScript中的数字类型,运算符应该是双重赋值而不是三重赋值,如下所示:

x % 2 == 0

请记住声明你的变量,显然这行不能单独编写。 :-)通常用作if语句。希望这会有所帮助。

答案 10 :(得分:0)

希望这会有所帮助。

let number = 7;

if(number%2 == 0){      

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

}else{

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

}

这是一项完整的功能,它将把输入的奇偶校验记录到控制台。

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

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

  }else{

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

  }
}

答案 11 :(得分:-1)

array = [1,2,3,4,5,6,7,8,9,10]

array.each {| x |如果x%2 == 0}

则放x

红宝石:D

2 4 6 8 10

相关问题