Underscore.js:如何链接自定义函数 [英] Underscore.js: how to chain custom functions

查看:116
本文介绍了Underscore.js:如何链接自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Underscore.js ,我可以编写以下内容,返回 42

Using Underscore.js, I can write the following which returns 42:

_([42, 43]).chain()
    .first()
    .value()

我有自定义函数,不是Underscore.js的一部分 double()

I have custom function, not part of Underscore.js called double():

function double(value) { return value * 2; };

我希望能够在Underscore链中调用此函数,就像它是下划线。我想写下面的内容,我想返回 84

I would like to be able to call this function in an Underscore chain, as if it was part of Underscore. I would like to write the following, which I'd like to return 84:

_([42, 43]).chain()
    .first()
    .double()
    .value()

由于Underscore没有定义 double(),所以这是行不通的。我可以使用 tap() 作为在:

This can't work since Underscore doesn't define double(). I could use tap() as in:

_([42, 43]).chain()
    .first()
    .tap(double)
    .value()

这是有效的,但 tap 将函数应用于其参数并返回参数,而不是函数的结果。所以在我看来,我需要一种 tap ,它返回应用于其参数的函数的结果。 Underscore.js中有这样的事吗?我错过了一些非常明显的东西吗?

This is valid, but tap applies the function to its argument and returns the argument, not the result of the function. So it looks to me like I would need a sort of tap that returns the result of the function applied to its argument. Is there anything like this in Underscore.js? Am I missing something terribly obvious?

推荐答案

没有找到 tap 返回由函数返回的值is runs,我定义一个我可以取并添加到 _ : p>

Not finding a tap that returns the value returns by the function is runs, I define one which I can take and add to _:

_.mixin({take: function(obj, interceptor) {
    return interceptor(obj);
}});

然后假设我有:

Then assuming I have:

function double(value) { return value * 2; };

我可以这样写:

I can write:

_([42, 43]).chain()
    .first()             // 42
    .take(double)        // Applies double to 42
    .value()             // 84

您可以看看 take 作为 map 在对象上,而不是列表中。想要试验这个吗?请参阅 jsFiddle示例

You can look at take as map on objects, instead of lists. Want to experiment with this? See this example on jsFiddle.

这篇关于Underscore.js:如何链接自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆