前端面试题之 sum(2)(3) (链式调用,toString,柯里化,数组操作)

写一个函数让下面两个输出结果相同;
console.log(sum(2)(3));
console.log(sum(2,3));
var sum = (function() { var list = []; var add = function() { // 拼接数组 var args = Array.prototype.slice.call(arguments); list = list.concat(args); return add; } // 覆盖 toString 方法 add.toString = function() { // 计算总和 var sum = list.reduce(function(pre, next) { return pre + next; }); // 清除记录 list.length = 0; return sum; } return add; })(); var s=sum(2, 3 ,4)(3)(1,2); console.log(s.toString()); console.log(sum(2, 3 ,4).toString()); console.log(sum(2, 3 ,4).toString()); console.log(sum(2)(3)(4).toString()); console.log(sum(2)(3)(4).toString());

 

posted @ 2017-07-21 19:14  茹孟凯  阅读(1201)  评论(0编辑  收藏  举报