简体   繁体   English

如何通过Java的Filter方法传递要过滤的值和用作条件的值?

[英]How to pass values to filter and values to use as a condition with the Filter method of Javascript?

I'm trying to Pass the values [1, 2, 3, 1, 2, 3] to be removed using the funcion "destroyer" and the values 2, 3 (or even more values ex: 1,3,5.) to be removed from the previous array. 我正在尝试传递值[1、2、3、1、2、3],以使用功能“销毁者”和值2、3(甚至更多的值,例如:1、3、5)删除。从上一个数组中删除。 Always the first part is an array to remove from and followed by numbers to remove from the array 始终第一部分是要从数组中删除的数组,然后是要从数组中删除的数字

Here you have the code that I have to solve: 这里有我必须解决的代码:

function destroyer(arr) {
  // Remove all the values
  return arr;
}

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

Try this approach. 试试这种方法。 It uses the spread operator and the includes() function 它使用传播运算符include()函数

... - is a spread operator ...-是点差操作员

 function destroyer(arr, ...items) { return arr.filter(i => !items.includes(i)); } let arr = destroyer([1, 2, 3, 1, 2, 3], 2, 3); console.log(arr); 

You can access all parameters passed to a function using arguments variable. 您可以使用arguments变量访问传递给函数的所有参数。 Note, this is an array like object but not an array, so you will have to convert it to array. 注意,这是一个类似于对象的数组,但不是数组,因此您必须将其转换为数组。 When you do that, your arr will be the first value as even that is a part of parameters. 当您这样做时,您的arr将是第一个值,即使它是参数的一部分。 You can use .slice(1) to get all values from second element. 您可以使用.slice(1)从第二个元素获取所有值。

ES5 ES5

 function destroyer(arr) { var args = [].slice.call(arguments,1); return arr.filter(function(val){ return args.indexOf(val) < 0 }) } console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); 

ES6 ES6

 function destroyer(arr) { var args = Array.from(arguments).slice(1); return arr.filter(x=>!args.includes(x)); } console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); 

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

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