美文网首页
add(1)(2)(3)

add(1)(2)(3)

作者: wrs瑞 | 来源:发表于2021-03-05 10:40 被阅读0次

一道常见的面试题

```

function add () {

    let res = [...arguments].reduce((a, b)=>{

        return a+b;

    }, 0);

    let temp=function() { // 使用闭包

        if(arguments.length){

            res+=[...arguments].reduce((a, b)=>{

                return a+b;

            }, 0);          // 累加

            return temp;         

        } else {

            return res;

        }

    }

    temp.toString = function() { // 重写toSting() 方法

        return res;

    }

    return temp; // 返回一个函数

}

console.log(add(1,2,3)()) //6

console.log(add(1,2,3)) //f 6

console.log(add(1)(3)) // f 4

console.log(add(1)(3)(5)()) //9

```

相关文章

网友评论

      本文标题:add(1)(2)(3)

      本文链接:https://www.haomeiwen.com/subject/lyrzfltx.html