freeCodeCamp中JavaScript filter()函数使用错误求助
Let's break down what's going wrong here and fix it step by step:
Root Causes of the Error
Misunderstanding Function Parameters
Your functiondestroyer(arr)only receives the first argument (the array[1, 2, 3, 1, 2, 3]) asarr. The subsequent values2and3aren't part ofarr—they're separate, unused parameters in your current code. When you loopi from 1 to arr.length-1, you're actually iterating over the elements of the input array, not the values you want to exclude.Incorrectly Accessing
arr[0]arritself is the target array you need to filter.arr[0]refers to the first element of that array (the number1), and numbers don't have afiltermethod—this is exactly why you're seeing the "filter isn't a function" error.Returning an Empty Array
You declaredvar 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
filteron 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

