关于取余运算代码中0和1底层作用的技术咨询
Hey there! Let's break this down nice and clear—those 0 and 1 in the modulus (%) operations are all about checking whether a number is even or odd, and here's exactly how they work for your two code snippets:
第一段代码:判断奇数的逻辑
if(13 % 2 !== 0) { alert ("Your age is odd!"); }
First, let's recall what the modulus operator does: a % b gives you the remainder when you divide a by b.
When you divide 13 by 2, you get 6 with a remainder of 1 (since 2*6=12, 13-12=1). So 13 % 2 equals 1.
The condition !== 0 is checking if that remainder is not equal to 0. Here's the key:
- Any even number divided by 2 will have a remainder of 0 (e.g., 12%2=0, 14%2=0)
- Any odd number divided by 2 will have a remainder of 1 (e.g.,13%2=1,15%2=1)
So in this code, 0 represents the "signature remainder" of even numbers. When the remainder isn't 0 (like with 13), we know the number is odd, so the alert fires.
第二段代码:反向判断偶数的逻辑
if(13% 2 !== 1) { alert (""); }
Again, 13%2 is 1. The condition here checks if the remainder is not equal to 1.
Since 1 is the signature remainder for odd numbers, a remainder that isn't 1 means the number is even. For example, if you replaced 13 with 12, 12%2=0, which is not equal to 1—so the condition would be true, and the (empty) alert would run.
In this snippet, 1 is the marker for odd numbers; if the remainder doesn't match this marker, we're dealing with an even number.
Quick Recap
When working with % 2:
0= the number is even (divisible by 2 with no remainder)1= the number is odd (divisible by 2 with 1 left over)
These two values are the only possible remainders when dividing any integer by 2, so they're perfect for quick even/odd checks!
内容的提问来源于stack exchange,提问作者Philip Malangmei

