谁能告诉我一些代码,以确定一个数字在JavaScript是偶数还是奇数?
当前回答
奇数除以2剩下余数为1,偶数除以0剩下余数为0。因此我们可以使用这段代码
function checker(number) {
return number%2==0?even:odd;
}
其他回答
if (X % 2 === 0){
} else {
}
用你的数字替换X(可以来自一个变量)。If语句在数字为偶数时运行,Else语句在数字为奇数时运行。
如果你只想知道某个给定的数字是否是奇数:
if (X % 2 !== 0){
}
同样,用一个数字或变量替换X。
像许多语言一样,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)
这是测试偶数的一个非常常见的习惯用法。
我是否需要创建一个包含很多偶数的大数组
不。使用模量(%)。它给出了你要除的两个数的余数。
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.
这意味着,如果你对任何数字x取余2,你得到的结果不是0就是1或者-1。0表示它是偶数。其他的都是奇数。
我将实现这个来返回一个布尔值:
function isOdd (n) {
return !!(n % 2);
// or ((n % 2) !== 0).
}
它对无符号数和有符号数都有效。当模量返回-1或1时,它将被转换为true。
Non-modulus解决方案:
var is_finite = isFinite;
var is_nan = isNaN;
function isOdd (discriminant) {
if (is_nan(discriminant) && !is_finite(discriminant)) {
return false;
}
// Unsigned numbers
if (discriminant >= 0) {
while (discriminant >= 1) discriminant -= 2;
// Signed numbers
} else {
if (discriminant === -1) return true;
while (discriminant <= -1) discriminant += 2;
}
return !!discriminant;
}
这可以用一小段代码来解决:
function isEven(value) {
return !(value % 2)
}
希望这对你有所帮助。