javascript - 使用 lodash _.flow 过滤、减少、映射
问题描述
作为一个在函数式编程中应用lodash库的初学者,我发现它._flow
并没有执行放入的函数。我的问题是如何在流中应用map、reduce或filter?还是我做错了什么?非常感谢任何帮助。
例如:
const _=require('lodash');
const scores = [50, 6, 100, 0, 10, 75, 8, 60, 90, 80, 0, 30, 110];
const newArray=_.filter(scores,val=>val<=100);
const newArray2=_.filter(newArray,val=>val>0);
console.log(newArray2);
// the output is
/*[
50, 6, 100, 10, 75,
8, 60, 90, 80, 30
]*/
但是,当我将它设为两个独立的函数并放入流时,它什么也没做。
const newRmvOverScores=_.filter(val=>val<=100);
const newRmvZeroScores=_.filter(val=>val>0);
const aboveZeroLess100=_.flow(newRmvOverScores,newRmvZeroScores)(scores);
console.log(aboveZeroLess100);
// the output is:
/*[
50, 6, 100, 0, 10, 75,
8, 60, 90, 80, 0, 30,
110
]*/
我找到了几个参考资料:
[1]使用 lodash,为什么 flow 中的 map 方法不起作用? [2] https://lodash.com/docs/4.17.15#flow
解决方案
两个问题:
- 定义
newRmvOverScores
and时newRmvZeroScores
,您实际上已经执行_.filter
了 , 并且没有集合参数。它们应该是函数 _.flow
需要一个函数数组,但您不提供数组,参数函数也没有(因为上一点)
这是更正后的脚本:
const scores = [50, 6, 100, 0, 10, 75, 8, 60, 90, 80, 0, 30, 110];
const newRmvOverScores = scores => _.filter(scores, val=>val<=100);
const newRmvZeroScores = scores => _.filter(scores, val=>val>0);
const aboveZeroLess100 = _.flow([newRmvOverScores,newRmvZeroScores])(scores);
console.log(aboveZeroLess100);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
推荐阅读
- labview - Labview:将控件保存在一定大小下
- typescript - 我们如何从 apollo-server 模块传递 ApolloServer 中的数据源和合并的 graphql 模式和解析器?
- symfony - 从 Symfony 3.4 中的参数读取 getParameter null
- ios - Game Center 未经身份验证,在 iOS 12 中请求身份验证
- r - R闪亮:在完成所有observeEvent代码之前更新tabsetpanel
- c++ - 动态数组模板类:ostream& 运算符友元函数的问题
- xaml - 使用 Visual Studio 2017 Xamarin 创建嵌入式 ListView
- excel - 将数据复制到新工作表,不包括最后 4 行
- sql - 为什么这个新的可为空的时间戳字段包含我添加到具有预先存在记录的表之后的值?
- python - 使用 pandas str.replace 执行全字子字符串替换