简体   繁体   English

如何遍历这些参数以筛选数组?

[英]How do I iterate through these arguments to filter an array?

So I have this code, which does what it needs to do, which is return an input array minus any values that match the arguments after the array. 所以我有这段代码,它可以完成所需的工作,即返回一个输入数组减去与该数组后面的参数匹配的所有值。 But, I am having trouble figuring out how to iterate through all the arguments. 但是,我在弄清楚如何遍历所有参数时遇到了麻烦。 Here is what I have working - 这是我的工作-

function destroyer(arr) {
  var arg2 = arguments[1];
  var arg3 = arguments[2];
  var arg4 = arguments[3];
  var result = arr.filter(function(arg) {
    if (arg != arg2 && arg != arg3 && arg != arg4) {
      return (arg);
    }
  });
  return result;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

And here is my attempt at iterating through all arguments with a for loop. 这是我尝试使用for循环遍历所有参数的尝试。 It is not working and I am struggling to conceptualize what exactly I am pumping through my callback in the arr.filter here - 它不起作用,我正在努力概念化我在此处通过arr.filter中的回调确切地注入的内容-

function destroyer(arr) {
  var result = arr.filter(function(arg) {
    for (var i = 1; i < arguments.length; i++) {
      if (arg != arguments[i]) {
        return (arg);
      }
    }
  });
  return result;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Is this close to where I need to be or am I way off here? 这离我需要去的地方很近吗?

The arguments variable is set on each function call, including the call to your .filter() callback. 在每个函数调用(包括对.filter()回调的调用.filter()上都设置arguments变量。 Thus arguments in that callback is not what you think it is. 因此,该回调中的arguments不是您所想的。

You can do what you're trying to do with .indexOf , and you'll need to copy they arguments into another array: 您可以使用.indexOf来完成您想做的.indexOf ,并且需要将它们的参数复制到另一个数组中:

function destroyer(arr) {
  var badValues = [];
  for (var i = 1; i < arguments.length; ++i)
    badValues = arguments[i];
  return arr.filter(function(value) {
    return badValues.indexOf(value) < 0;
  });
}

It's popular to use .slice() to copy all or part of the arguments object: 使用.slice()复制全部或部分arguments对象很流行:

  var badValues = [].slice.call(arguments, 1);

You can do that if you like the brevity, but passing the arguments object out of a function makes it very hard to optimize. 如果您希望简洁,可以执行此操作,但是将arguments对象传递给函数会使优化变得非常困难。

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

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