Create chain in lodash with custom functions

后端 未结 3 2062
天命终不由人
天命终不由人 2020-12-10 05:23

Is there way to get my own custom function in a chain of lodash. So for example like this:

var l = [1,2,3]
var add = function(a, b){return a+b}

var r =_.cha         


        
3条回答
  •  忘掉有多难
    2020-12-10 05:40

    What you look for is a way to extend the lodash prototype. It so nicely turns out that you can do it easily with a mixin utility function. Check here the docs: http://lodash.com/docs#mixin

    In your example it will look like:

    var l = [1,2,3];
    var  add = function(a, b){return a+b}
    
    
    _.mixin({
        add: add 
    });
    
    
    var r =_.chain(l).find(function(a){return a>1}).add(5).value()
    console.log(r); ==> 7
    

    and here is live sample on fiddle: http://jsfiddle.net/g2A9C/

提交回复
热议问题