简体   繁体   English

在freecodecamp中使用Javascript filter()函数时出错

[英]Error using Javascript filter() function in freecodecamp

function destroyer(arr) {

var arry=[];


for(var i=1;i<arr.length;i++)
{
  arr[0] = arr[0].filter(cc => cc != arr[i]);
}
return arry;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

I basically have to return all the elements of the first sub-array which arent present in the rest of array. 我基本上必须返回数组其余部分中存在的第一个子数组的所有元素。

Its displaying "arr[0].filter isnt a function. destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1]. I basically have to return all the elements of the first sub-array which arent present in the array. 它显示的“ arr [0] .filter不是一个函数。destroyer([1,2,3,1,2,3],2,3)应该返回[1,1]。我基本上必须返回所有的元素存在于数组中的第一个子数组。

You aren't doing anything with the other arguments provided to the destroyer function - you have to test those arguments against arr , you shouldn't be testing arr against itself. 您不会对提供给destroyer函数的其他参数做任何事情-您必须针对arr测试这些参数,而不应该针对自身测试arr

 function destroyer() { const [arr, ...excludeArr] = arguments; return arr.filter(elm => !excludeArr.includes(elm)); } console.log( destroyer([1, 2, 3, 1, 2, 3], 2, 3) ); 

 function destroyer(arr, x, y) { return arr.filter(item => (item != x) && (item != y)) } console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)) 

 const destroyer = (arr, ...args) => { return arr.filter(item => args.indexOf(item) < 0); }; const result = destroyer([1, 2, 3, 1, 2, 3], 2, 3); console.log(result); 

You forgot to call your method using the array. 您忘记了使用数组调用方法。 you have to surround it with another pair of [] . 您必须用另一对[]包围它。

You can simply return the filtered arr[0] to get what you want. 您只需返回过滤后的arr[0]就可以得到想要的。

 function destroyer(arr) { for (var i = 1; i < arr.length; i++) { arr[0] = arr[0].filter(cc => cc != arr[i]); } return arr[0]; } console.log(destroyer([[1, 2, 3, 1, 2, 3], 2, 3])); 

as you said you should filter first subarray but you are sending only 1 array with int values and other values as argument, the actual usage of this function should be 就像您说的那样,您应该过滤第一个子数组,但是您只发送一个带有int值和其他值作为参数的数组,该函数的实际用法应为

 function destroyer(arr) { for(var i = 1; i < arr.length; i++) { arr[0] = arr[0].filter(cc => cc != arr[i]); } return arr[0]; } destroyer([[1, 2, 3, 1, 2, 3], 2, 3]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM