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

freeCodeCamp中JavaScript filter()函数使用错误求助

Fixing the "arr[0].filter isn't a function" Error in Your freeCodeCamp Solution

Let's break down what's going wrong here and fix it step by step:

Root Causes of the Error

  1. Misunderstanding Function Parameters
    Your function destroyer(arr) only receives the first argument (the array [1, 2, 3, 1, 2, 3]) as arr. The subsequent values 2 and 3 aren't part of arr—they're separate, unused parameters in your current code. When you loop i from 1 to arr.length-1, you're actually iterating over the elements of the input array, not the values you want to exclude.

  2. Incorrectly Accessing arr[0]
    arr itself is the target array you need to filter. arr[0] refers to the first element of that array (the number 1), and numbers don't have a filter method—this is exactly why you're seeing the "filter isn't a function" error.

  3. Returning an Empty Array
    You declared var arry=[] but never populate it, so even if your filtering logic worked, you'd still return an empty array instead of the desired result.

Corrected Solutions

Here are two clean ways to implement the function correctly:

Option 1: Use Rest Parameters (Modern JavaScript)

This is the most readable approach for modern environments:

function destroyer(arr, ...excludeValues) {
  // Filter the input array to keep elements NOT in excludeValues
  return arr.filter(item => !excludeValues.includes(item));
}

// Test it out
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // Output: [1, 1]

Option 2: Use arguments (For Older Browser Compatibility)

If you need to support older environments that don't have rest parameters:

function destroyer(arr) {
  // Extract all arguments after the first one (the values to exclude)
  var excludeValues = Array.prototype.slice.call(arguments, 1);
  // Filter elements that aren't in the exclude list
  return arr.filter(item => excludeValues.indexOf(item) === -1);
}

// Test it out
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // Output: [1, 1]

How These Fixes Work

  • Both versions first collect all the values you want to exclude (the arguments after the initial array).
  • They then use filter on the original input array to keep only elements that don't appear in the exclude list.
  • No more modifying non-array values or returning empty arrays—this directly gives you the expected [1, 1] result.

内容的提问来源于stack exchange,提问作者Ketan Pandey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:30:15