Javascript 有人能解释Java脚本中的reduce函数吗

Javascript 有人能解释Java脚本中的reduce函数吗,javascript,Javascript,有人能解释一下这个JavaScript代码中发生了什么吗?我不理解以[]作为初始值传递I.reduce的部分: function longestString(i) { // It will be an array like (['big',[0,1,2,3,4],'tiny']) // and the function should return the longest string in the array // This should flatten an arra

有人能解释一下这个JavaScript代码中发生了什么吗?我不理解以
[]
作为初始值传递
I.reduce
的部分:

function longestString(i) {
    // It will be an array like (['big',[0,1,2,3,4],'tiny'])
    // and the function should return the longest string in the array

    // This should flatten an array of arrays
    var r = i.reduce(function(a, b) {
        return a.concat(b);
    }, []);

    // This should fetch the longest in the flattened array
    return r.reduce(function (a, b) 
    { 
        return a.length > b.length ? a : b; 
    });
}

reduce中的初始值是累加器。例如,如果i是
[[1],[2],[3]]
,则reduce语句相当于:

r = [];
r = r.concat([1]);
r = r.concat([2]);
r = r.concat([3]);

在reduce的每个步骤中,必须对两个参数调用函数。在第一步中,必须有一些初始值。你不能什么都不打电话给.concat,所以你从一个空数组开始。

我尽可能地澄清了你的问题,但我仍然不确定你在问什么。你是在问为什么通过了
[]
?或者它是做什么的?或者在网上找文件?不管用吗?输出有什么问题吗?如果没有,谷歌是一个更合适的提问地点,因为它对函数有详细的描述。我问传递[]作为参数有什么用,只是为了澄清,如果提供了初始值,
reduce
从索引
0
开始。如果不是,则从索引
1
开始,使用索引
0
作为初始值。