Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用函数式编程过滤到多个路径_Javascript_Functional Programming - Fatal编程技术网

Javascript 如何使用函数式编程过滤到多个路径

Javascript 如何使用函数式编程过滤到多个路径,javascript,functional-programming,Javascript,Functional Programming,我有以下伪代码: let array = getData(); array.filter(x => condition1(x)).doSomething1... array.filter(x => condition2(x)).doSomething2... array.filter(x => condition3(x)).doSomething3... 显然,这是无效的,因为它将数组迭代3次 我想知道是否有一种方法可以做到: array.filterMany([ x

我有以下伪代码:

let array = getData();
array.filter(x => condition1(x)).doSomething1...
array.filter(x => condition2(x)).doSomething2...
array.filter(x => condition3(x)).doSomething3...
显然,这是无效的,因为它将数组迭代3次

我想知道是否有一种方法可以做到:

array.filterMany([
    x => condition1(x).doSomething1...,
    x => condition2(x).doSomething2...,
    x => condition3(x).doSomething3...
])

使数组只迭代一次?

您可以使用array reduce功能

例如:

const arr=[1,2,3,4,5,6,7,8,9,10];
常量拆分=arr.reduce(([奇数,偶数],当前)=>{
如果(当前%2==0){
偶压(电流);
}否则{
奇压(电流);
}
返回[奇数,偶数];
}, [[], []]);

控制台日志(“奇数/偶数”,拆分)您可以使用array reduce功能

例如:

const arr=[1,2,3,4,5,6,7,8,9,10];
常量拆分=arr.reduce(([奇数,偶数],当前)=>{
如果(当前%2==0){
偶压(电流);
}否则{
奇压(电流);
}
返回[奇数,偶数];
}, [[], []]);

控制台日志(“奇数/偶数”,拆分)像这样的东西怎么样

const condition1=x=>x==1;
常量条件2=x=>x==2;
常量条件3=x=>x==3;
[1,2,3]。映射(n=>{
条件1(n)和&console.log('foo');
条件2(n)和控制台日志('bar');
条件3(n)和控制台日志('baz');

})
像这样的东西怎么样

const condition1=x=>x==1;
常量条件2=x=>x==2;
常量条件3=x=>x==3;
[1,2,3]。映射(n=>{
条件1(n)和&console.log('foo');
条件2(n)和控制台日志('bar');
条件3(n)和控制台日志('baz');

})
您可以将条件放入一个数组中,并使用进行检查


您可以将这些条件放入一个数组中,并使用进行检查



你能提供一个更清晰的例子吗?使用array reduce。你能不能只使用logical“and”
&&
?@clabe45我想根据条件做不同的事情?你能提供一个更清晰的例子吗?使用array reduce。你能不能只使用logical“and”
&&
?@clabe45我想根据条件做不同的事情谢谢。我只能在7分钟内帮忙@MotKohn:-)如果同一个值有可能满足多个条件,请确保将该
If/else
转换为一系列
If
s@当然可以。好主意,谢谢。我只能在7分钟内帮忙@MotKohn:-)如果同一个值有可能满足多个条件,请确保将该
If/else
转换为一系列
If
s@当然可以。这是个好主意。你希望
.map
函数做什么?@Neal只不过是一个
forEach
!也许这在语义上更精确。你希望
.map
函数做什么?@Neal只不过是一个
forEach
!也许这在语义上更为精确。
var conditions = [condition1, condition2, condition3],
    filtered = array.filter(a => conditions.every(c => c(a)));