You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于取余运算代码中0和1底层作用的技术咨询

理解取余运算中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:14:09