[Javascript] Advanced Reduce: Additional Reducer Arguments

Sometimes we need to turn arrays into new values in ways that can't be done purely by passing an accumulator along with no knowledge about its context. Learn how to reduce an array of numbers into its mathematical mean in a single reduce step by using the optional index and array reducer arguments.

function reducer(accumulator, value, index, array) {
var intermediaryValue = accumulator + value; if (index === array.length - 1) {
return intermediaryValue / array.length;
} return intermediaryValue;
} var data = [1, 2, 3, 3, 4, 5, 3, 1];
var mean = data.reduce(reducer, 0); console.log(mean);
上一篇:七牛整合PHP上传文件


下一篇:C#利用NPOI生成具有精确列宽行高的Excel文件