qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!

Home Page:https://github.com/qappleh/Interview

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

第6题(2019-07-29):实现一个函数add,满足下列输出结果

qappleh opened this issue · comments

commented
add(1); // 1
add(1)(2); // 3
add(1)(2)(3); // 6
add(1)(2,3); // 6
add(1,2)(3); // 6
add(1,2,3); // 6  
commented

答案:

function add(){
	var args = [...arguments];
	var fn = function(){
	   args.push(...arguments);
	   return fn;
	}
	fn.tostring = function(){
	    return args.reduce((x,y) => x + y)
	}
	return fn;
}
console.log(add(1,2)); // 3
console.log(add(1)(2)); // 3
console.log(add(1)(2)(3)); // 6
console.log(add(1,2,3)(4)); // 10  
commented

不知道哪里出错了,控制台的结果输出的是一个fn函数