谁能告诉我一些代码,以确定一个数字在JavaScript是偶数还是奇数?
当前回答
if (X % 2 === 0){
} else {
}
用你的数字替换X(可以来自一个变量)。If语句在数字为偶数时运行,Else语句在数字为奇数时运行。
如果你只想知道某个给定的数字是否是奇数:
if (X % 2 !== 0){
}
同样,用一个数字或变量替换X。
其他回答
使用下面的代码:
函数 isOdd(num) { return num % 2;} console.log(“1 is ” + isOdd(1)); console.log(“2 is ” + isOdd(2)); console.log(“3 is ” + isOdd(3)); console.log(“4 is ” + isOdd(4));
1表示奇数,0表示偶数。
像许多语言一样,Javascript有一个模运算符%,用于查找除法的余数。如果数除2后无余数,则该数为偶数:
// this expression is true if "number" is even, false otherwise
(number % 2 == 0)
同理,若2除后余数为1,则该数为奇数:
// this expression is true if "number" is odd, false otherwise
(number % 2 == 1)
这是测试偶数的一个非常常见的习惯用法。
奇数除以2剩下余数为1,偶数除以0剩下余数为0。因此我们可以使用这段代码
function checker(number) {
return number%2==0?even:odd;
}
一个可以传递的简单函数。使用模运算符%:
var is_even = function(x) {
return !(x % 2);
}
is_even(3)
false
is_even(6)
true
你可以这样做:
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}