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

数组Filter方法未按预期工作,求排查Codecademy迭代器练习问题

Fixing Your Filter Issue with Unnecessary Words

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 (returns true/false)
  • The ! flips that boolean: now we get false for words we want to remove, and true for 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:41:10