这个功能可以用 Array.prototype 方法完成吗

Can this function be done with Array.prototype method

我正在尝试采用新的 Array.prototype 函数,想知道如何用它来完成这段代码。

目标是,return将原始对象数组中每12个对象的平均值作为数组。

var WeatherData = [{tm:0,t:22,h:15,p:537}..
var AverageWeather = []; 
var temp = 0;

for (i = 0; i < WeatherData.length; i++) {

    temp += WeatherData[i].t;
    if ((i+1) % 12 == 0) {
    AverageWeather.push( Math.round((temp / 12) * 100) / 100 );
    Temp = 0;
    }
}

console.log(AverageWeather);

fiddle: https://jsfiddle.net/xd2v62rL/

Array.prototype.getAverageWeather = function() {
    var AverageWeather = []; 
    var temp = 0;

    for (i = 0; i < this.length; i++) {

        temp += this[i].t;
        if ((i+1) % 12 == 0) {
      AverageWeather.push( Math.round((temp / 12) * 100) / 100 );
        Temp = 0;
        }
    }

    return AverageWeather;
}

var WeatherData = [{tm:0,t:22,h:15,p:537},{tm:5,t:13,h:42,p:895},{tm:10,t:21,h:36,p:582},{tm:15,t:22,h:51,p:986},{tm:20,t:21,h:36,p:902},{tm:25,t:22,h:58,p:439},{tm:30,t:16,h:57,p:1042},{tm:35,t:20,h:14,p:480},{tm:40,t:20,h:34,p:958},{tm:45,t:17,h:7,p:403},{tm:50,t:13,h:69,p:460},{tm:55,t:20,h:36,p:967},{tm:60,t:19,h:57,p:419},{tm:65,t:18,h:43,p:746},{tm:70,t:17,h:49,p:344},{tm:75,t:16,h:90,p:651},{tm:80,t:19,h:96,p:646},{tm:85,t:19,h:3,p:301},{tm:90,t:14,h:96,p:770},{tm:95,t:17,h:54,p:1036},{tm:100,t:15,h:79,p:890},{tm:105,t:22,h:32,p:1041},{tm:110,t:22,h:67,p:415},{tm:115,t:20,h:82,p:616}];

console.log(WeatherData.getAverageWeather());

这样您就可以将函数附加到 Array 原型。

您可以为此结合使用 reduce 和 map

 let averages = WeatherData
 .reduce(groupInto12, [])
 .map(getAverage);

function groupInto12(rows, key, index){
    if(index % 12 === 0)
       rows.push([key])
    else
       rows[rows.length-1].push(key)
       return rows;
}
function getAverage (tempfor12days) {
  let totalTemp = tempfor12days.reduce((acc,val)=>acc+val.t,0);
  return Math.round((totalTemp / 12) * 100) / 100;
 }

当您在尝试计算平均值之前将数据分成 12 组时,使用 Array.prototype 方法 map reduce 等可以更容易地解决这个问题:

var weatherData = [{tm:0,t:22,h:15,p:537},{tm:5,t:13,h:42,p:895},{tm:10,t:21,h:36,p:582},{tm:15,t:22,h:51,p:986},{tm:20,t:21,h:36,p:902},{tm:25,t:22,h:58,p:439},{tm:30,t:16,h:57,p:1042},{tm:35,t:20,h:14,p:480},{tm:40,t:20,h:34,p:958},{tm:45,t:17,h:7,p:403},{tm:50,t:13,h:69,p:460},{tm:55,t:20,h:36,p:967},{tm:60,t:19,h:57,p:419},{tm:65,t:18,h:43,p:746},{tm:70,t:17,h:49,p:344},{tm:75,t:16,h:90,p:651},{tm:80,t:19,h:96,p:646},{tm:85,t:19,h:3,p:301},{tm:90,t:14,h:96,p:770},{tm:95,t:17,h:54,p:1036},{tm:100,t:15,h:79,p:890},{tm:105,t:22,h:32,p:1041},{tm:110,t:22,h:67,p:415},{tm:115,t:20,h:82,p:616}];

var groups = [];

while(weatherData.length) {
    groups.push(weatherData.splice(0, 12));
}

var averageWeather = groups.map(function(g) {
    return Math.round((g.reduce(function(acc, val) { 
       return acc + val.t
    }, 0) / 12) * 100) / 100;
});

console.log(averageWeather);