给定一组对象

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或其他库,是否有通用的方法可以做到这一点?

最佳答案

使用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

关于javascript - 计算对象不同属性的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35252014/

10-11 01:23