简体   繁体   English

使用%模数了解此Javascript代码

[英]Understanding this Javascript code using % modulus

Im currently in process of learning Javascript. 我目前正在学习Javascript。 And I have seen the following code, which confuses me. 而且我看到了以下代码,这使我感到困惑。

Description of code: 代码说明:
Starting on line 1, the function isOdd takes a number n and returns a boolean (true or false) stating whether the number is odd or not. 从第1行开始,函数isOdd接受数字n,并返回一个布尔值(true或false),说明该数字是否为奇数。

Code

var isOdd = function (n) {
      if (n % 2 === 0) {
        return false;
      } else {
        return true;
      }
    };

    var isEven = function(n) {
        if(n % 2 === 0) {
            return true;
        } else {
            return false;
        }
    };

Where I am confused. 我感到困惑的地方。
The code: 编码:

n % 2 === 0

I have always taken the following to be the description for %: 我一直将以下内容作为对%的描述:

% Is the modulus operator. It returns the remainder of dividing number1 by number2.

Which would mean that the if statement in the function isOdd returns false is the difference between n and 2 is 0. But its meant to mean if n is divisible by 2 (even) return false. 这意味着函数isOdd中的if语句返回false是n和2之间的差为0。但是,这意味着如果n可被2(偶数)整除,则返回false。

I just dont see how its doing that. 我只是不知道它是如何做到的。

In my mind, if we take the even number 30. Apply it to n % 2. We get 15, which is remainder of dividing 30 by 2. 15 does not equal 0, but 30 is an even number, and with this code it would be seen as odd. 在我看来,如果我们将偶数设为30,将其应用于n%2。我们得到15,这是30除以2的余数。15不等于0,但是30是偶数,使用此代码被认为是奇怪的。

Can someone explain this? 有人可以解释吗?

The line in question: 有问题的行:

  if (n % 2 === 0) {
    return false;
  }

Means "if when you divide n by 2 the remainder is zero, then return false (ie n is not odd)". 表示“如果将n除以2,则余数为零,则返回false(即n不为奇数)”。

The "remainder" is whatever is left over when you subtract the nearest multiple, so for example "64 % 10" is 4, since the nearest multiple of 10 is 60, leaving 4. 当减去最接近的倍数时,“余数”就是剩下的值,例如,“ 64%10”为4,因为10的最接近倍数为60,剩下4。

Taking your example and putting it another way, 30/2 is 15, 30%2 is zero (ie whatever is left over after 30/2). 举个例子,换句话说,30/2是15,30%2是零(即30/2之后剩下的东西)。 Here's more info on the remainder after division. 这是除后剩余部分的更多信息。

You're confusing Quotient and Remainder . 您会混淆商数余数 When you divide 30 by 2, integer quotient is 15, and remainder is 0. You can also calculate remainder by multiplying integer quotient by divisor and subtracting it from dividend. 将30除以2时,整数商为15,余数为0。您还可以通过将整数商除以除数并从除数中减去来计算余数。 So for this division remainder is 30 (dividend) - 15 (quotient) * 2 (divisor) = 0. 因此,对于该除法,余数为30(股息)-15(商)* 2(除数)= 0。

If n can be divided by 2 it means it's even -> 如果n可以除以2,则表示它是偶数->
which means it's not odd -> 这并不奇怪->
isOdd is false isOdd为假

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM