JavaScript 过滤器数组

标签 javascript arrays

我正在参加在线 JavaScript 类(class),我对其中一项任务感到好奇:

我们提供了一个初始数组(破坏函数中的第一个参数),后跟一个或多个参数。我们必须从初始数组中删除与这些参数具有相同值的所有元素。

这是我的解决方案,但它不起作用:

 function destroyer(arr) {
   // Separating the array from the numbers, that are for filtering; 
   var filterArr = [];
   for (var i = 1; i < arguments.length; i++) {
     filterArr.push(arguments[i]);
   }

   // This is just to check if we got the right numbers
   console.log(filterArr);

   // Setting the parameters for the filter function
   function filterIt(value) {
       for (var j = 0; j < filterArr.length; j++) {
         if (value === filterArr[j]) {
           return false;
         }
       }
     }
     // Let's check what has been done
   return arguments[0].filter(filterIt);
 }

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

我找到了解决方案,但对我来说没有任何意义,这就是我发布这个问题的原因;你能告诉我为什么下面的代码有效吗:

function destroyer(arr) {
  // Separating the array from the numbers, that are for filtering; 
  var filterArr = [];
  for (var i = 1; i < arguments.length; i++) {
    filterArr.push(arguments[i]);
  }

  // This is just to check if we got the right numbers
  console.log(filterArr);

  // Setting the parameters for the filter function
  function filterIt(value) {
      for (var j = 0; j < filterArr.length; j++) {
        if (value === filterArr[j]) {
          return false;
        }
        // This true boolean  is what makes the code to run and I can't                  // understand why. I'll highly appreciate your explanations.
      }
      return true;
    }
    // Let's check what has been done
  return arguments[0].filter(filterIt);
}

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

感谢您的提醒!

最佳答案

您可以通过使用 Array.prototype.reduce() 来使用相对简单的代码完成相同的工作,如下所示;

ES6

var destroyer = (a,...f) => a.reduce((p,c) => f.includes(c) ? p : p.concat(c),[]);
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

或者在 ES5 中

function destroyer(a){
  var f = Array.prototype.slice.call(arguments,1);
  return a.reduce(function(p,c){
                    return f.indexOf(c) !== -1 ? p : p.concat(c);
                  },[]);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

关于JavaScript 过滤器数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40630734/

相关文章:

javascript - 如何在不提交表单的情况下通过按键盘上的 Enter 来获取文本值

python - 在循环的条件语句中调用 len() 可以吗?

jquery - 如何在 JavaScript 中合并两个带有嵌套数组的对象?

python - 如何舍入一个numpy数组?

arrays - 提高在结构 slice 中搜索值的性能

arrays - 如何从 ruby​​ 中的哈希数组的范围中找到最小值?

javascript - 通过类名获取内容 javascript

javascript - 正则表达式匹配长度超过 5 个字符且具有两个连续数字的密码

javascript - 发布时更改 oData 条目中的属性。 [WCF 数据服务 + EF + SQL Express]

javascript - 通过多选隐藏/显示表格行