Javascript函数挑战add(1,2)和add(1)(2)都应该返回3 [英] Javascript function challenge add(1,2) and add(1)(2) both should return 3

查看:526
本文介绍了Javascript函数挑战add(1,2)和add(1)(2)都应该返回3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个朋友挑战我写一个适用于这两种情况的函数。

A friend of mine challenged me to write a function that works with both of these scenarios

add(2,4)  // 6
add(2)(4) // 6

我的直觉是编写一个add()函数返回自己,但我不知道我朝正确的方向。此失败。

My instinct was the write an add() function that returns itself but I'm not sure I'm heading in the right direction. This failed.

function add(num1, num2){
    if (num1 && num2){
        return num1 + num2;
    } else {
        return this;
    }
}

alert(add(1)(2));

所以我开始阅读返回其他函数或返回自己的函数。

So I started reading up on functions that return other functions or return themselves.

http://davidwalsh.name/javascript-functions
JavaScript:自调用函数返回一个闭包。它是什么?
JavaScript:自调用函数返回一个闭包。是什么?

我会继续努力,但如果有人有一个光滑的解决方案,我很愿意看到它! / p>

I am going to keep trying, but if someone out there has a slick solution, I'd love to see it!

推荐答案

Dr.Dobs Journal上有一篇文章 JavaScript中的Currying和部分函数,其中描述了这个问题。

There is an article on Dr.Dobs Journal about "Currying and Partial Functions in JavaScript" which describes exactly this problem.

本文中找到的一个解决方案是:

One solution found in this article is:

// a curried add
// accepts partial list of arguments
function add(x, y) {
     if (typeof y === "undefined") { // partial
        return function (y) {
              return x + y;
        };
     }
   // full application
   return x + y;
}

这篇关于Javascript函数挑战add(1,2)和add(1)(2)都应该返回3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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