Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - 如何使console.log(sum(1))// 1和console.log(sum(1,2)(3))// 6工作?(How can I make console.log(sum(1)) // 1 and console.log(sum(1,2)(3)) //6 work?)

sum如何制作console.log(sum(1))// 1和console.log(sum(1,2))// 3和console.log(sum(1,2)(3))// 6工作?

  ask by 道小铿 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Return a function that, when stringified, returns a number in a closure, which gets added to when the function is called:(返回一个函数,该函数在进行字符串化处理后会在闭包中返回一个数字,该数字会在调用该函数时添加到其中:)

 const sum = (...args) => { let thisSum = 0; const fn = (...args) => { thisSum += args.reduce((a, b) => a + b, 0); return fn; }; fn.toString = () => thisSum; return fn(...args); }; console.log(sum(1)) // 1 console.log(sum(1, 2)) // 3 console.log(sum(1, 2)(3)) //6 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...