js 实现 add函数?

函数实现累加计算,其实就是函数科里化的一个过程,

add(1) => 1

add(1)(2) => 3

add(1)(2)(3) => 6

1、通过闭包原理以及toString方法

function add(...a) {
   let res = 0;
   a.forEach(item => (res += item));
   let fn = function(...b) {
      b.forEach(item => (res += item));
      return fn;
   };
   fn.toString = function() {
      return res;
   };
   return fn;
}

console.log(add(1, 2)(3)+'');
console.log(add(1)(2, 3) + '');
console.log(add(1, 2, 3) + '');

2、通过rest参数实现

 

posted @ 2021-02-14 19:29  程序員劝退师  阅读(418)  评论(0编辑  收藏  举报