使用自定义函数在lodash中创建链
问题描述:
有没有办法在lodash链中获得我自己的自定义函数.因此,例如:
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 =_.chain(l).find(function(a){return a>1}).add(5).value()
=>r = 7
答
您要寻找的是扩展lodash原型的方法.事实证明,您可以使用mixin实用程序功能轻松完成此操作.在这里检查文档: http://lodash.com/docs#mixin
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
这是小提琴上的实时示例: http://jsfiddle.net/g2A9C/
and here is live sample on fiddle: http://jsfiddle.net/g2A9C/