zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Advanced Reduce: Additional Reducer Arguments

JavaScript reduce arguments Advanced reducer
2023-09-14 08:59:20 时间

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);