删除数组中的值等于后续参数

时间:2015-08-06 23:18:20

标签: javascript

我希望这个函数能够工作并生成数组[1,1],为什么它不起作用?

 function destroyer(arr) {
      return arr.reduce(function(a,b){
         if (arguments.slice(1).every(function(arg){
             return arg !== b;
         })) a.push(b);
         return a;
      }, []);
    }

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

2 个答案:

答案 0 :(得分:3)

我建议

function destroyer(arr) {
  return [].slice.call(arguments, 1).reduce(function(arr, num) {
    return arr.filter(function(item) {
      return num !== item;
    });
  }, arr);
}

或者,在ES6中,

function destroyer(arr, ...unwanted) {
  return unwanted.reduce((arr,num) => arr.filter(item => num !== item), arr);
}

答案 1 :(得分:0)

<强> jsFiddle Demo

arguments不是数组。它是“阵列式的”。你需要调用数组原型。此外,splice每次调用时都会修改数组,所以它只能使用一次。

function destroyer(arr) {
  //access the array prototype,
  //splice first element off of argument array,
  //and store result
  var args = [].splice.call(arguments,1);
  return arr.reduce(function(p,c){
   //indexOf is an easy way to look for existence in an array
   if( args.indexOf(c) == -1 ) p.push(c);
   return p;
  }, []);
}

在您的输入上调用此内容,destroyer([1, 2, 3, 1, 2, 3], 2, 3)将生成[1,1]