Find if variable is divisible by 2

前端 未结 12 499
梦谈多话
梦谈多话 2020-12-07 19:22

How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.

相关标签:
12条回答
  • 2020-12-07 20:04

    array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    array.each { |x| puts x if x % 2 == 0 }

    ruby :D

    2 4 6 8 10

    0 讨论(0)
  • 2020-12-07 20:17

    Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:

    x % 2 == 0
    

    Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.

    0 讨论(0)
  • 2020-12-07 20:18

    Hope this helps.

    let number = 7;
    
    if(number%2 == 0){      
    
      //do something;
      console.log('number is Even');  
    
    }else{
    
      //do otherwise;
      console.log('number is Odd');
    
    }
    

    Here is a complete function that will log to the console the parity of your input.

    const checkNumber = (x) => {
      if(number%2 == 0){      
    
        //do something;
        console.log('number is Even');  
    
      }else{
    
        //do otherwise;
        console.log('number is Odd');
    
      }
    }
    
    0 讨论(0)
  • 2020-12-07 20:20

    You don't need jQuery. Just use JavaScript's Modulo operator.

    0 讨论(0)
  • 2020-12-07 20:21

    You can do it in a better way (up to 50 % faster than modulo operator):

    odd: x & 1 even: !(x & 1)

    Reference: High Performance JavaScript, 8. ->Bitwise Operators

    0 讨论(0)
  • 2020-12-07 20:23

    Use modulus:

    // Will evaluate to true if the variable is divisible by 2
    variable % 2 === 0  
    
    0 讨论(0)
提交回复
热议问题