JavaScript咖喱函数 [英] JavaScript curry function

查看:132
本文介绍了JavaScript咖喱函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过以下方式实现了curry函数:

I have implemented a curry function this way:

function curry (fn) {
    var slice = Array.prototype.slice,
        args = slice.apply(arguments, [1]);
    return function () {
        fn.apply(null, args.concat(slice.apply(arguments)));
    };
}

当我使用上述功能执行以下操作

When I use the above function to do the following

function add (x, y) {
    return x + y;
}

var inc = curry(add, 1);
console.log(inc(10));

它记录undefined. 11不是预期的输出吗?我的代码有什么问题?

it logs undefined. Isn't 11 the expected output? What is wrong with my code?

注意:在add功能内使用console.log(x, y)记录1 10.我不明白为什么它返回undefined.

Note: Using console.log(x, y) inside the add function logs 1 10. I don't understand why it returns undefined.

推荐答案

您在咖喱函数中缺少return.

return function () {
    return fn.apply(null, args.concat(slice.apply(arguments)));
};

这似乎可行:)

这篇关于JavaScript咖喱函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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