【问题标题】:Filter, reduce, map with lodash _.flow使用 lodash _.flow 过滤、减少、映射
【发布时间】:2021-05-21 03:54:13
【问题描述】:

作为一个在函数式编程中应用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]Using lodash, why is the map method within flow not working? [2]https://lodash.com/docs/4.17.15#flow

【问题讨论】:

    标签: javascript functional-programming lodash


    【解决方案1】:

    两个问题:

    • 在定义newRmvOverScoresnewRmvZeroScores 时,您实际上已经执行 _.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);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 2020-02-25
      • 2016-01-22
      • 2016-01-18
      • 2010-10-23
      • 2015-06-14
      相关资源
      最近更新 更多