js 函数柯里化和闭包的使用

函数的柯里化

f(x)(y)就是柯里化:使用函数f,输入x,计算,获得一个新的函数,再次输入y,计算,获取结果。f(x)(y)(z)(a)(b)(c),你完全可以写这样的函数。每次进行一次计算时,都返回一个新的函数。当然,你也可以写成这样的方式g(x, y, z, a, b, c)

  var add = function (num) {
        return function (y) {
            return num + y;
        }
    }
    console.log(add(2)(3))  //5

函数柯里化和闭包的使用

求和

var add = function (...args) {
       const target = (...args1)=>add(...[...args,...args1])
       target.getValue=()=>args.reduce((p,n)=>p+n,0)
       return target;
    }
    console.log(add(2,3,4).getValue()) 
    console.log(add(2,3,4)(3)(4).getValue()) 
    console.log(add(2)(3)(4).getValue()) 
请用今天的努力,让明天没有遗憾。
原文地址:https://www.cnblogs.com/cupid10/p/14706138.html