谁能告诉我一些代码,以确定一个数字在JavaScript是偶数还是奇数?
当前回答
通过使用三元运算符,我们可以找到奇数和偶数:
Var num = 2; 结果= (num % 2 == 0) ?'even': '奇数' console.log(结果);
其他回答
像许多语言一样,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)
这是测试偶数的一个非常常见的习惯用法。
使用下面的代码:
函数 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中更函数化的方法:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const negate = f=> (...args)=> !f(...args)
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = negate(isOdd)
你可以这样做:
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }