JavaScript使用过滤器和循环从数组中删除多个值

问题描述:

我是新来的,在编写函数 destroyer()从数组中删除多个值时需要一些帮助.

I'm new here and need some help with writing a function destroyer() to remove multiple values from an array.

destroyer()函数传入一个数组和其他数字作为参数.这个想法是从数组中删除数字.

The destroyer() function passes in an array and additional numbers as arguments. The idea is to remove the numbers from the array.

例如

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

输出: [1,1]

destroyer(["tree", "hamburger", 53], "tree", 53) 

输出: [汉堡"]

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

输出: []

注意:这些示例仅显示另外两个要删除的数字.但是功能destroyer()应该能够删除任意数量的值(即4、5或6个参数).

Note: the examples only show 2 additional numbers to remove. But the function destroyer() should be able to remove any number of values (i.e. 4, 5, or 6 parameters).

但是,我的代码无法产生相同的结果.具体来说,使用console.log,我发现我的过滤器功能无法正常循环.

However, my code does not produce the same result. Specifically, using console.log, I see that my filterer function does not loop properly.

1)有人可以帮助我进行调试吗?

1) Can anyone help me debug?

2)编写此函数的更好方法?

2) Any better way to write this function?

非常感谢您!

function destroyer() {

  var args = Array.prototype.slice.call(arguments); 

  var itemToRemove = args.slice(1);
  console.log(itemToRemove);
  var newArr = args[0];
  console.log(newArr);

  function filterer(value) { 

    for (var i = 0; i < itemToRemove.length; i++) {
      console.log(i);
      console.log(itemToRemove[i]);
      if (value != itemToRemove[i]) {
        return value;
      }
    } 
   }

  return newArr.filter(filterer);
}

您的 filterer 函数可以更简单:

function filterer (value) {
    return itemToRemove.indexOf(value) === -1;
}