简体   繁体   English

如何将函数嵌入到javascript这样的函数中?

[英]How to embed functions into functions in javascript like this?

I've just met with a very interesting task to solve, but I can't do it myself. 我刚刚遇到了一个非常有趣的任务要解决,但是我自己做不到。

Make a function which do the following input! 进行以下输入的功能!

console.log(foo(4)(5)(6)); // output: 120

The solution is not this: 解决方案不是这样的:

function foo(number1,number2,number3){
  return number1 * number2 * number3;
}

In theory it has to use nested functions. 理论上,它必须使用嵌套函数。

It is called currying . 这被称为咖喱 You need to return function which it's case returns a function which returns the total. 您需要返回函数,这种情况是返回一个返回总数的函数。 Here we also use a term called closure . 在这里,我们还使用了称为闭包的术语。

 function foo(a){ return function(b) { return function(c){ return a * b * c; } } } console.log(foo(4)(5)(6)); 

With ES6 syntax 使用ES6语法

 var foo = a => b => c => a*b*c; console.log(foo(4)(5)(6)); 

For infinite levels you can do 对于无限的水平,你可以做

 function foo(value){ infinite.total = value; function infinite(val) { infinite.total *= val; return infinite; } infinite.toString = function() { return infinite.total; } return infinite; } console.log(foo(4)(5)(6)(7)); var total = foo(4)(5)(6)(7); console.log(total); 

But this will output the total in that cases, when toString() is called explicitly or implicitly 但是在这种情况下,当显式或隐式调用toString()时,这将输出总计

You could use an approach for any length of repeated calls of the function with returning a function and an implementation of toString method. 您可以对返回的函数和toString方法的实现使用任意长度的函数重复调用方法。

 var foo = function(value) { function fn(a) { fn.value *= a; return fn; } fn.value = value; fn.toString = function () { return fn.value; }; return fn; } console.log(foo(4)(5)(6)); console.log(foo(42)); console.log(foo(42)(44)); 

try with currying : 尝试currying

function foo(number) {
  return function(number2) {
    return function(number3) {
      return number * number2  number3;
    }
  }
}

console.log(foo(5)(6)(7));

https://jsfiddle.net/mv9bm3tL/1/ https://jsfiddle.net/mv9bm3tL/1/

More information : https://www.sitepoint.com/currying-in-functional-javascript/ 详细信息: https : //www.sitepoint.com/currying-in-functional-javascript/

You need nested functions - currying;

console.log(foo(4)(5)(6)); // output: 120


let first = foo(4);
let second = first(5);
let last = second(6);

console.log(last);

function foo(number1,number2,number3){
  return function(number2){
    return function(number3){
      return number1 * number2 * number3;
    }
  }
}

Closures in javascript will help you to achieve this. javascript中的闭包将帮助您实现这一目标。

function foo(a){
  return function(b){
    return function(c){
      return a*b*c;
    }
  }
}

console.log(foo(4)(5)(6)); //will return 120

Using arrow functions; 使用箭头功能;

 var foo = a => b => c => a*b*c; console.log(foo(4)(5)(6)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM