如何编写“sum(2,3)”和“sum(2)(3)”的输出为5的函数 [英] How to Write a function where the output for both “sum(2,3)” and “sum(2)(3)” will be 5

查看:404
本文介绍了如何编写“sum(2,3)”和“sum(2)(3)”的输出为5的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮我写这个函数
写一个函数,其中sum(2,3)和sum(2)(3)的输出将是5



我认为我们需要使用close来编写函数!

解决方案

语法如下: sum(2)(3) currying 有关。这意味着你需要在main函数中返回另一个函数来获得所需的结果。



这是关于 currying 的一个很好的视频href =https://www.youtube.com/watch?v=iZLP4qOwY8I\"rel =nofollow noreferrer> Youtube ,我从中学到了很多东西。



  function sum(a){if(arguments.length == 1){return function(b){return a + b; } else {return Object.keys(arguments).reduce((a,b)=> arguments [a] + arguments [b]); }}的console.log(总和(2,3));执行console.log(总和(2)(3));  



Karl-AndréGagnon建议,它也可以用 bind 函数完成。



  function sum(a){if(arguments.length == 1){return sum.bind(this,a)} else {return Object.keys(arguments).reduce((a ,b)=> arguments [a] + arguments [b]); }}的console.log(总和(2,3));执行console.log(总和(2)(3));  


Can Anybody help me to write this function Write a function where the output for both "sum(2,3)" and "sum(2)(3)" will be 5

I think we need to write function using closer!

解决方案

Syntax as follows: sum(2)(3) is related with currying. It means that you need to return another function inside the main function to get the desired result.

Here's a nice video about currying on Youtube, from which I've learned a lot.

function sum(a){
  if (arguments.length == 1) {
    return function(b){
      return a + b;
    }
  } else {
    return Object.keys(arguments).reduce((a,b) => arguments[a] + arguments[b]);
  }
}

console.log(sum(2,3));
console.log(sum(2)(3));

As Karl-André Gagnon proposed, it can be also done with bind function.

function sum(a){
  if (arguments.length == 1) {
    return sum.bind(this, a)
  } else {
    return Object.keys(arguments).reduce((a,b) => arguments[a] + arguments[b]);
  }
}

console.log(sum(2,3));
console.log(sum(2)(3));

这篇关于如何编写“sum(2,3)”和“sum(2)(3)”的输出为5的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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