Determine whether the natural numbers are odd or even

Topic request

Code implementation

 <script>
    // The user enters a number
    var n = Number(prompt("Please enter a number"));
    // Check if it is a natural number.
    if (0 <= n && Math.floor(n) === n) {
      // is a natural number
      // Check whether it is odd
      if (n % 2! =0) {
        alert("Is odd.");
      } else {
        alert("Even"); }}else {
      alert("Not a natural number.");
    }
  </script>
Copy the code

Topic difficulty

Summary of several methods to judge integers

1. Use modular arithmetic

if(num%1= = =0) {
  // num is an integer
}
Copy the code

2. Use Math methods: Round, floor, ceil

if(Math.round(num) === num) {
  // num is an integer
}

if(Math.floor(num) === num) {
  // num is an integer
}

if(Math.ceil(num) === num) {
  // num is an integer
}
Copy the code

3. Use the Number method isInteger

if(Number.isInteger(num)) {
  // num is an integer
}
Copy the code

This method is a new one in ES6, and polyfill is shown below

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === 'number' && 
    isFinite(value) && 
    Math.floor(value) === value;
};
Copy the code