数组Filter方法未按预期工作,求排查Codecademy迭代器练习问题
Hey there! Let's figure out why your filter isn't removing those unnecessary words like you expected—this is a common small logic mix-up, easy to fix!
The Problem in Your Code
Take a look at your filter callback:
let betterWords = storyWords.filter(function(word) { return word != unnecessaryWords.includes(word); });
Here's what's going wrong: unnecessaryWords.includes(word) returns a boolean (true if the word is in the disabled list, false otherwise). When you compare word != boolean, JavaScript does a weird type-coerced check that doesn't align with your goal.
For example, if the word is "extremely", includes returns true—then you're checking if "extremely" != true, which evaluates to true. That means the filter keeps the word instead of tossing it out!
The Simple Fix
You just need to negate the boolean result from includes() directly. The filter should keep words that are not in the unnecessary list, so return the opposite of whether the word is found:
let betterWords = storyWords.filter(function(word) { return !unnecessaryWords.includes(word); });
If you prefer shorter syntax, an arrow function works too:
let betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));
Why This Works
unnecessaryWords.includes(word)checks if the current word is a disabled term (returnstrue/false)- The
!flips that boolean: now we getfalsefor words we want to remove, andtruefor words we want to keep - Filter only keeps elements where the callback returns
true, so this correctly strips out your unnecessary words
Give this a try, and your console output should finally show the cleaned-up array you're aiming for!
内容的提问来源于stack exchange,提问作者sikarak

