计算对象的不同属性的值

时间:2016-02-07 09:53:25

标签: javascript

给定一个对象数组

function Example(x, y){
  this.prop1 = x;
  this.prop2 = y;
}
var exampleArray = new Array();
exampleArray.push(nex Example(0,1));
exampleArray.push(nex Example(1,3));

现在我想添加一个函数来计算其中一个属性

的平均值
function calcAvg(exampleArray, 'prop1') -> 0.5
function calcAvg(exampleArray, 'prop2') -> 2

如果我不想使用jQuery或其他库,是否有通用的方法来执行此操作?

4 个答案:

答案 0 :(得分:1)

我认为它会起作用, 您需要迭代数组中的所有Example个对象,并将给定属性的值添加到变量中,例如sum然后在最后将其除以数组中的对象总数以获得平均值。

console.log(avg(exampleArray, 'prop1'));

function avg (array, propName){
     var sum = 0;
     array.forEach(function(exm){ 
        sum+= exm[propName];  
    });
    return sum / array.length;
}

答案 1 :(得分:1)

此代码遍历arr的每个值,在每个值中搜索属性prop,将该属性的值推送到名为values的数组,并返回所有值的总和values中的值除以其中的值数。

function calcAvg(arr,prop){
  var values = [];
  for(var i = 0; i<arr.length; i++){
    values.push(arr[i][prop]);
  }
  var sum = values.reduce(function(prev,current){
     return prev+current;
  });
  return sum/values.length;
}

演示is here.

答案 2 :(得分:1)

您可以使用Array.prototype.reduce()

  

reduce()方法对累加器和数组的每个值(从左到右)应用函数以将其减少为单个值。

function Example(x, y) {
    this.prop1 = x;
    this.prop2 = y;
}

function calcAvg(array, key) {
    return array.reduce(function (r, a) {
        return r + a[key];
    }, 0) / array.length;
}

var exampleArray = [new Example(0, 1), new Example(1, 3)],
    avgProp1 = calcAvg(exampleArray, 'prop1'),
    avgProp2 = calcAvg(exampleArray, 'prop2');

document.write(avgProp1 + '<br>');
document.write(avgProp2);

答案 3 :(得分:1)

使用Array.prototype.reduce方法解决并检查有效属性:

function Example(x, y) {
    this.prop1 = x;
    this.prop2 = y;
}
var exampleArray = new Array();
exampleArray.push(new Example(0, 1));
exampleArray.push(new Example(1, 3));

function calcAvg(arr, prop) {
    if (typeof arr[0] === 'object' && !arr[0].hasOwnProperty(prop)) {
        throw new Error(prop + " doesn't exist in objects within specified array!");
    }

    var avg = arr.reduce(function(prevObj, nextObj){
        return prevObj[prop] + nextObj[prop]; 
    });

    return avg/arr.length;
}

console.log(calcAvg(exampleArray, 'prop2')); // output: 2
相关问题