简体   繁体   中英

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. It is not working and I am struggling to conceptualize what exactly I am pumping through my callback in the arr.filter here -

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. Thus arguments in that callback is not what you think it is.

You can do what you're trying to do with .indexOf , and you'll need to copy they arguments into another array:

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:

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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