函数柯里化 java_js 函数柯里化 闭包

参考

一个统计求和的函数

需要知道整个数组的信息,然后遍历求值

function countMoney() {

let money = 0

// 温馨提示:arguments是所接收的所有参数组成的类数组,不懂的需要搜一搜补补知识啦

for (let i = 0; i < arguments.length; i++) {

money += arguments[i]

}

return money

}

// 把全部数据都输入进行计算

money = countMoney(1, 1, 2, 2, 3, 3, 4, 4)

console.log(money); // 20

// 藏了一年的账本记录的数据

const records = [1, 1, 2, 2, 3, 3, 4, 4]

// 解构赋值

money = countMoney(...records)

console.log(money); // // 20

柯里化

利用闭包保存数据,注意多次执行时,args数组中的数据以及money的变化情况

如果有参数,将参数加入args,返回函数,没有参数,遍历args求money总数

const countMoney = (function () {

let money = 0

let args = []

const res = function () {

if (arguments.length === 0) {

for (let i = 0; i < args.length; i++) {

money += args[i]

}

return money

} else {

// arguments 是个类数组来着,应该用展开符展开才能push进去

args.push(...arguments)

return res

}

}

return res

})()

// 2018-01-01 存了1毛钱

countMoney(1)

// 2018-01-02 存了2毛钱

countMoney(2)

// 2018-01-03 存了3毛钱

countMoney(3)

// 2018-01-04 存了4毛钱

console.log(countMoney(4)); // [Function: res]

//一年以后

// 统计这笔巨额存款 输出结果为 10

console.log(countMoney()) //10

// 你还可以装逼地进行花式统计,

// 单独执行的话结果同样是10

// 由于闭包机制这里将1234加入到args后又遍历求和了一次

console.log(

countMoney(1)(2)(3)(4)() // 30

);

转载至链接:https://my.oschina.net/ahaoboy/blog/1930099

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值