数组中的平均和

时间:2014-03-18 17:29:40

标签: javascript arrays

我有以下数组

  DataArray = [{
    "Year": "Year 7",
        "test1": 28,
        "test2": 19,
         "test3": 22,
         "average": ''

}, {
    "Year": "Year 8",
        "test1": 15,
        "test2": 28,
        "test3": 22,
        "average": ''           

}, {
    "Year": "Year 9",
        "test1": 25,
        "test2": 24,
         "test3": 22,
        "average": ''
 }, {
    "Year": "Year 10",
        "test1": 26,
        "test2": 19,
         "test3": 22,
        "average": ''            
}, {
    "Year": "Year 11",
        "test1": 48,
        "test2": 52,
         "test3": 22,
        "average": ''            
}];

我怎样才能使'average'的值是每个对象中test 1,test 2和test 3的平均值?

4 个答案:

答案 0 :(得分:6)

dataArray.forEach(function(x) { x.average = (x.test1 + x.test2 + x.test3)/3 });

仅适用于应该是最现代浏览器的browsers that support forEach

另请注意,dataArray应该camelCase它是javascript中高度推荐的命名约定,除了应该调用的函数外,所有内容都以小写字母开头new

答案 1 :(得分:3)

如果您需要早于IE 9支持,您可以这样做:

for (var i = 0, data; i < DataArray.length; i ++) {
    data = DataArray[i];
    data.average = (data.test1 + data.test2 + data.test3) / 3;
}

答案 2 :(得分:1)

您可以通过简单的循环实现它:

var avg = 0;
for(i in DataArray) {
    avg = DataArray[i]["test1"] + DataArray[i]["test2"] + DataArray[i]["test3"];
    DataArray[i]["average"] = avg / 3;
    alert(DataArray[i]["average"]);
}

答案 3 :(得分:1)

这是其他人都注意到的基本想法。我已经使用jQuery将值输出到屏幕。否则,此解决方案不需要它。

dataArray.forEach(function (e, i) {

    var average = Math.floor((e.test1 + e.test2 + e.test3) / 3);

    $('<span />', {
        text: e.test1 + ' + ' + e.test2 + ' + ' + e.test3 + ' / = ' + average
    }).appendTo('body');

    e.average = average;
});

console.log(dataArray);

http://jsfiddle.net/z6FGg/