# 如何确定JavaScript中数字是否为奇数

2020/10/09 18:21 · javascript ·  · 0评论

``````function 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代表偶数。

``````function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}

function checkNumber(argNumber) {
document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);
}

checkNumber(17);``````
``<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>``

``````var isOdd = function(x) { return x & 1; };
var isEven  = function(x) { return !( x & 1 ); };
``````

``````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); }
``````

``````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.
``````

``````function isEven(value) {
return !(value % 2)
}
``````

``````var isEven=n=>(n&1)?"odd":"even";
``````

``````// this expression is true if "number" is even, false otherwise
(number % 2 == 0)
``````

``````Number.prototype.isEven=function(){
return this % 2===0;
};

Number.prototype.isOdd=function(){
return !this.isEven();
}
``````

``````var a=5;
a.isEven();
``````

==假

`````` a.isOdd();
``````

==真

``````if(a.isOdd){
a.isOdd();
}
``````

``````(5).isOdd()
``````

# 性能：

``````var is_even = function(x) {
return !(x % 2);
}

is_even(3)
false
is_even(6)
true
``````
``````   <script>
function even_odd(){
var num =   document.getElementById('number').value;

if ( num % 2){
document.getElementById('result').innerHTML = "Entered Number is Odd";
}
else{
document.getElementById('result').innerHTML = "Entered Number is Even";
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Find Given Number is Even or Odd </h2>
<p>Enter a value</p>
<input type="text" id="number" />
<button onclick="even_odd();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
``````

``````if (X % 2 === 0){
} else {
}
``````

``````if (X % 2 !== 0){
}
``````

``````for (var i=1; i<=5; i++)
if (i%2 !== 0) {
console.log(i)
}
``````

``````    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

</head>
<body bgcolor = "#FFFFCC">
<h3 align ="center"> ODD OR EVEN </h3><table cellspacing = "2" cellpadding = "5" bgcolor="palegreen">
<form name = formtwo>
<td align = "center">
<center><BR />Enter a number:
<input type=text id="enter" name=enter maxlength="10" />
<input type=button name = b3 value = "Click Here" onClick = compute() />
<b>is<b>
<input type=text id="outtxt" name=output size="5" value="" disabled /> </b></b></center><b><b>
<BR /><BR />
</b></b></td></form>
</table>

<script type='text/javascript'>

function compute()
{
var enter = document.getElementById("enter");
var outtxt = document.getElementById("outtxt");

var mynmb = enter.value;
if (isNaN(mynmb))
{
outtxt.value = "error !!!";
alert( 'please enter a valid number');
enter.focus();
return;
}
else
{
if ( mynmb%2 == 0 ) { outtxt.value = "Even"; }
if ( Math.abs(mynmb%2) == 1 ) { outtxt.value = "Odd"; }
}
}

</script>
</body>
</html>
``````

``````function isOdd(value) {
return typeof value === "number" && // value should be a number
isFinite(value) &&                // value should be finite
Math.floor(value) === value &&    // value should be integer
value % 2 !== 0;                  // value should not be even
}
``````

``````function isOdd(value) {
return Number.isInteger(value)      // value should be integer
value % 2 !== 0;                  // value should not be even
}
``````

``````isOdd();         // false
isOdd("string"); // false
isOdd(Infinity); // false
isOdd(NaN);      // false
isOdd(0);        // false
isOdd(1.1);      // false
isOdd("1");      // false
isOdd(1);        // true
isOdd(-1);       // true
``````

``````var isOdd = function(num) {
return 'number'!==typeof num ? 'NaN' : !!(num % 2);
};
``````

``````var isEven = function(num) {
return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
};
``````

``````isOdd(5); // true
isOdd(6); // false
isOdd(12); // false
isOdd(18); // false
isEven(18); // true
isEven('18'); // 'NaN'
isEven('17'); // 'NaN'
isOdd(null); // 'NaN'
isEven('100'); // true
``````

ES6中的一根衬垫只是因为它很干净。

`const isEven = (num) => num % 2 == 0;`

## 许多人误解了奇数的含义

• `isOdd("str")`应该是假的。

只有整数可以是奇数。
• `isOdd(1.223)`并且`isOdd(-1.223)`应该是错误的。

浮点数不是整数。
• `isOdd(0)`应该是假的。

零是一个偶数整数（
https://en.wikipedia.org/wiki/Parity_of_zero）。
• `isOdd(-1)`应该是真的。

这是一个奇数整数。

## 解

``````function isOdd(n) {

// Must be a number
if (isNaN(n)) {
return false;
}

// Number must not be a float
if ((n % 1) !== 0) {
return false;
}

// Integer must not be equal to zero
if (n === 0) {
return false;
}

// Integer must be odd
if ((n % 2) !== 0) {
return true;
}

return false;
}
``````

JS小提琴（如果需要）：https : //jsfiddle.net/9dzdv593/8/

## 1线

Javascript 1-线性解决方案。对于那些不关心可读性的人。

``````const isOdd = n => !(isNaN(n) && ((n % 1) !== 0) && (n === 0)) && ((n % 2) !== 0) ? true : false;
``````

`const isOdd = num => num % 2 == 1;`

``````  function checker(number)  {
return number%2==0?even:odd;
}
``````

``````    var num = 3 //instead get your value here
var aa = ["Even", "Odd"];

alert(aa[num % 2]);
``````

``````//Array of numbers
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,32,23,643,67,5876,6345,34,3453];
//Array of even numbers
var evenNumbers = [];
//Array of odd numbers
var oddNumbers = [];

function classifyNumbers(arr){
//go through the numbers one by one
for(var i=0; i<=arr.length-1; i++){
if (arr[i] % 2 == 0 ){
//Push the number to the evenNumbers array
evenNumbers.push(arr[i]);
} else {
//Push the number to the oddNumbers array
oddNumbers.push(arr[i]);
}
}
}

classifyNumbers(numbers);

console.log('Even numbers: ' + evenNumbers);
console.log('Odd numbers: ' + oddNumbers);
``````

``````function isOdd (n) {
return !!(n % 2);
// or ((n % 2) !== 0).
}
``````

``````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;
}
``````

``````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)
``````

``````var num = 2;
result = (num % 2 == 0) ? 'even' : 'odd'
console.log(result);``````

``````function evenOrOdd(numbers) {
const evenNumbers = [];
const oddNumbers = [];
numbers.forEach(number => {
if (number % 2 === 0) {
evenNumbers.push(number);
} else {
oddNumbers.push(number);
}
});

console.log("Even: " + evenNumbers + "\nOdd: " + oddNumbers);
}

evenOrOdd([1, 4, 9, 21, 41, 92]);
``````

``````function evenOrOdd(number) {
if (number % 2 === 0) {
return "even";
}

return "odd";
}

console.log(evenOrOdd(4));
``````