通过数组来过滤方法 [英] passing array to filter method

查看:121
本文介绍了通过数组来过滤方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能传递一个数组JavaScript中的过滤器的方法?

例如我想筛选与另一个数组的数组。
现在,我有我的code工作,但我没有传递数组,我滤波器阵列具有全局范围。有没有一种方法来传递数组有一个更清洁的code?

 变种数组= [1,2,3,4,5];
变种filterNumbers = [1,4];VAR的结果= array.filter(筛选数据);功能筛选数据(值){
  返回filterNumbers.indexOf(值)=== -1;
}


解决方案

您可以通过使用部分应用程序做到这一点(的小提琴):

 函数filterUsing(filterByArray){//获取数组通过过滤
    返回功能(值){//返回一个过滤功能
        返回filterByArray.indexOf(值)=== -1;
    };
}VAR filterFunc = filterUsing(filterNumbers); //使用filterNumbers阵列获取功能VAR的结果= array.filter(filterFunc);

How can I pass an array to the filter method in JavaScript?

For example I want to filter an array with another array. Now I have my code working but I am not passing the array, my filter array has a global scope. Is there a way to pass the array to have a cleaner code?

var array = [1, 2, 3, 4, 5];
var filterNumbers = [1, 4];

var result = array.filter(filterData);

function filterData(value) {
  return filterNumbers.indexOf(value) === -1;
}

解决方案

You can do this by using partial application (fiddle):

function filterUsing(filterByArray) { // get the array to filter by
    return function(value) { // return a filtering function
        return filterByArray.indexOf(value) === -1;
    };
}

var filterFunc = filterUsing(filterNumbers); // get the function using your filterNumbers array

var result = array.filter(filterFunc);

这篇关于通过数组来过滤方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆