简体   繁体   English

我如何为它制作一个 function 来跟踪第二个参数的空值

[英]How would i make a function for it as well which will keep track of the empty values of second argument

multiply(10)()()()(12) This a function call and we have to make a function to multiply 2 numbers multiply(10)()()()(12) 这是一个 function 调用,我们必须调用 function 来将 2 个数字相乘

You can curry the function and leverage rest parameters and spreading .您可以柯里化function并利用rest 参数传播 If there are no arguments supplied then (...args) will be an empty array and .bind(this, ...args) will create a function without partially applying any values to it.如果没有提供 arguments,则(...args)将是一个空数组,而.bind(this, ...args)将创建一个 function 而不对其应用任何值。

Once all arguments are satisfied, the function is immediately called.一旦满足所有 arguments,立即调用 function。

 const curry = f => function(...args) { if (f.length - args.length <= 0) return f.apply(this, args); return curry(f.bind(this, ...args)); } const mul = (a, b) => a * b; const multiply = curry(mul); console.log(multiply(10, 12)); // = 120 console.log(multiply(10)(12)); // = 120 console.log(multiply(10)()(12)); // = 120 console.log(multiply(10)()()()(12)); // = 120 const obj = { x: 2, multiply: curry(function(a, b) { return a * b * this.x; }) } console.log(obj.multiply(10)()()()(12)); // = 240

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

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