任何人都可以解释JavaScript中的reduce函数吗?

can any one explain reduce function in javascripts

本文关键字:函数 reduce 中的 都可以 解释 JavaScript 任何人      更新时间:2023-09-26

谁能解释一下这个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; 
    });
}

归约中的初始值是一个累加器。 例如,如果 i 是[[1],[2],[3]]则 reduce 语句等效于:

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

在reduce的每个步骤中,必须对两个参数调用该函数。 在第一步中,必须有一些初始值。 您不能无所事事地调用 .concat,因此您可以从一个空数组开始。