# 看一个题，谁能帮忙解释一下？这是一个关于reduce递归

``````var f = (function() {
let r = 1;
return function(...args){
r *= args.reduce((p, n) => p + n);
f.valueOf = () => r;    // 主要是这句代码，完全懵B
return f;
}
}());
+f(1,2,3)(2,3)(3,4,5)(6,7)
// 输出值为(1+2+3)*(2+3)*(3+4+5)*(6+7)的计算结果``````

1. reduce
2. valueOf
3. 递归
4. ...（涉及的没提到的）

4 个回答

1 `reduce` 配合 `args` 解构用来求每一个圆括号里面的和

``const sum = (...args) => args.reduce((i, j) => i + j)``

2 每次圆括号执行`f`都会再返回这个`f`，保证了这个`f`后面可以跟上无限多个圆括号

``````var j = (function() {
return function () {
console.log('yo')
return j
}
}())

j()()()() // yo yo yo yo``````

3 立即执行函数保证了每有一个圆括号都立即、顺序执行

``````var f = function() {
let r = 1
return function f(...args){
r *= args.reduce((p, n) => p + n)
console.log(args) // 第一个圆括号就不执行了
f.valueOf = () => r
return f
}
}``````

4 如果你只想得到返回的 `f` 函数，或者是只想让这个 `r` 存在于各个层级 `f` 的上下文中的话，`valueOf` 都没有出现的意义，但是如果你想从 `f()()()` 中把 `r` 取出来，就需要 `valueOf` 了。最后的加号会用到他，这里就返回当前上下文中的 `r`

``````var f = (function() {
let r = 1
return function f(...args){
r *= args.reduce((p, n) => p + n)
if (args.length == 2) return r // 如果你能找另外一个方式把 r 输出也是可以的
return f
}
}())
console.log(f(1,2,3)(2,3,5)(3,4,5)(6,7))``````
{"ft_lang_label":"__label__zh","ft_lang_prob":0.8488836,"math_prob":0.9998822,"size":495,"snap":"2020-24-2020-29","text_gpt3_token_len":353,"char_repetition_ratio":0.103869654,"word_repetition_ratio":0.0,"special_character_ratio":0.3919192,"punctuation_ratio":0.2020202,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99814606,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-06-04T20:51:51Z\",\"WARC-Record-ID\":\"<urn:uuid:44183dc7-0571-4d10-8da8-9d59d43ddf9b>\",\"Content-Length\":\"44569\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:c716fd08-b122-411b-8d93-14655393924e>\",\"WARC-Concurrent-To\":\"<urn:uuid:1474adaa-1ddc-408d-bb34-66273b7f6311>\",\"WARC-IP-Address\":\"103.61.39.86\",\"WARC-Target-URI\":\"https://segmentfault.com/q/1010000013946322/a-1020000013948397\",\"WARC-Payload-Digest\":\"sha1:L73EEDX3XIB3B757X2ZUS4ZYYAPFU5VN\",\"WARC-Block-Digest\":\"sha1:PZGE5OAXDTD72VWSBIFGN7CL2L4HFQEJ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-24/CC-MAIN-2020-24_segments_1590347458095.68_warc_CC-MAIN-20200604192256-20200604222256-00099.warc.gz\"}"}