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

如何正确实现严格比较与取模运算符?Udacity课程代码求助

Fixing Strict Comparison and Modulo Usage for Odd/Even Check

Hey there! Let's walk through how to adjust your code to meet the feedback requirements.

First off, your original code works logically because JavaScript treats 0 as falsy and non-zero values (like 1 or -1 from modulo operations) as truthy. But the feedback is asking for explicit strict comparison (using === or !== instead of relying on implicit truthiness checks), which is a great practice for clarity and avoiding unexpected type conversion issues.

Here's the corrected code with strict comparison and proper modulo usage:

var number = 19;
if (number % 2 !== 0) {
  console.log("odd");
} else {
  console.log("even");
}

Or if you prefer checking for even first (which might feel more intuitive):

var number = 19;
if (number % 2 === 0) {
  console.log("even");
} else {
  console.log("odd");
}

Why this works:

  • Strict comparison (===/!==): These operators check both value and type equality, so there’s no hidden type conversion happening. This is exactly what your feedback is calling for.
  • Modulo operator (%): For any integer, number % 2 returns 0 if it’s even, and either 1 or -1 if it’s odd (for example, -19 % 2 returns -1 in JavaScript). Checking if the result is strictly equal to 0 (for even) or strictly not equal to 0 (for odd) covers all integer cases—positive or negative.

Your original code did use the modulo operator, but it skipped the explicit strict comparison step. Adding that fixes the feedback issue while keeping your core logic intact.

内容的提问来源于stack exchange,提问作者Isabella Weems

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:17:57