如何正确实现严格比较与取模运算符?Udacity课程代码求助
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 % 2returns0if it’s even, and either1or-1if it’s odd (for example,-19 % 2returns-1in JavaScript). Checking if the result is strictly equal to0(for even) or strictly not equal to0(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

