在JavaScript过滤器方法中迭代
我试图比较函数的两个给定参数。具体问题如下: 将为您提供一个初始数组(destroyer函数中的第一个参数),后跟一个或多个参数。从初始数组中删除与这些参数值相同的所有元素 注 您必须使用arguments对象 日志(销毁程序([1,2,3,1,2,3],2,3));//预期产出:[1,1] 我正在使用filter方法迭代数组,但无法将args与过滤器回调中的数组元素进行比较在JavaScript过滤器方法中迭代,javascript,arrays,algorithm,filter,iteration,Javascript,Arrays,Algorithm,Filter,Iteration,我试图比较函数的两个给定参数。具体问题如下: 将为您提供一个初始数组(destroyer函数中的第一个参数),后跟一个或多个参数。从初始数组中删除与这些参数值相同的所有元素 注 您必须使用arguments对象 日志(销毁程序([1,2,3,1,2,3],2,3));//预期产出:[1,1] 我正在使用filter方法迭代数组,但无法将args与过滤器回调中的数组元素进行比较 function destroyer(arr, ...args) { let result = arr
function destroyer(arr, ...args) {
let result = arr.filter(num => {
for (let i = 0; i<=args.length; i++ ){
num !== args[i]
}
});
return result;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
函数销毁程序(arr,…args){
让结果=arr.filter(num=>{
对于(让i=0;i可能是使用的更容易实现目标的方法。此外,您可以使用…rest
所谓的“为您服务”函数,请参阅文档表单:
rest参数语法允许我们将不定数量的参数表示为数组
请尝试以下操作:
const destropher=(arr,…rest)=>{
返回arr.filter(num=>!rest.includes(num));
}
日志(销毁程序([1,2,3,1,2,3],2,3));
filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素
例如:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
通过
Filter遍历某个数组的所有元素并返回一个新数组。只有回调函数(作为Filter参数调用的函数)返回true时,它才会将元素放入新数组中,否则忽略它
接下来,值得使用rest参数来实现两个数组(初始值和要排除的值)
rest参数语法允许我们将不定数量的参数表示为数组
带说明的解决方案:
//Declare your function, first parameter is initial array, the second one is also array created by using rest parameters
function destroyer(initialArray = [], ...toExclude) {
// filter initialArray, if el (single element) is NOT included in "toExclude" it returns true
// and add this particular element to the result array
let result = initialArray.filter(el => toExclude.includes(el) == false);
//return result
return result;
}
//Declare your function, first parameter is initial array, the second one is also array created by using rest parameters
function destroyer(initialArray = [], ...toExclude) {
// filter initialArray, if el (single element) is NOT included in "toExclude" it returns true
// and add this particular element to the result array
let result = initialArray.filter(el => toExclude.includes(el) == false);
//return result
return result;
}