数组中对象属性的总和 [英] Sum of object properties within an array

查看:96
本文介绍了数组中对象属性的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含属性的数组,例如:

I have an array with properties, take the following for example:

var arrayPeople = [
    {
        name: 'joe',
        job: 'programmer',
        age: 25,
    },
    {
        name: 'bob',
        job: 'plumber',
        age: 30,
    };
];

我想创建一个能够返回平均年龄的函数,这是我目前所拥有的无法正常工作

I want to create a function that will return their average ages, here is what i have that is currently not working

var ageAverage = function(array) {
    var age = 0, average;
    for (var i = 0; i < array.length; i++) {
        age += array[i].age;
    }
    average = age / array.length;
    return average;
};

运行此功能时我得到的是非数字

What I am getting when running this function is Not A Number

但我可以上班的是:

var ageAverage = function(array) {
    var age = 0, average;
    for (var i = 0; i < array.length; i++) {
        age = array[0].age;
    }
    average = age / array.length;
    return average;
};

这里的细微差别是我带走了+ =并且只是做了=,我拿了离开我们的变量i的使用,只是给了它数组的第一个索引。所以在这样做时,我知道函数正确地用arrayPeople替换参数数组,但是我的for循环中出现了一些问题,即阻止我变为0和1(arrayPeople的索引)。

The subtle difference here is that I took away the += and just made it =, and i took away the use of our variable i and just gave it the first index of the array. So in doing this, I know that the function is correctly substituting the parameter array with arrayPeople, but there is something going wrong in my for loop that is stopping i from becoming 0 and 1 (the indexes of arrayPeople).

PS 我正在尝试自己做这件事,我不是在找人帮我做这个问题,我真的很感激一些提示关于修复什么或者我需要研究理解如何解决这个问题的概念。

P.S. I am trying to do this on my own, and I am not looking for someone to just do the problem for me, I would really appreciate just some hints on what to fix or maybe a concept I need to research the understand how to fix this problem.

谢谢!!

推荐答案

您需要初始化年龄变量( var age = 0

var arrayPeople = [{
  name: 'joe',
  job: 'programmer',
  age: 25,
}, {
    name: 'bob',
    job: 'plumber',
    age: 30,
}];

var ageAverage = function(array) {
  var age = 0,
      average;

  for (var i = 0; i < array.length; i++) {
    age += array[i].age;
  }

  average = age / array.length;
  return average;
};

console.log(
  ageAverage(arrayPeople)
);

在您的变体中, age 变量等于 undefined undefined + = number (例如25)返回 NaN ;

in your variant, age variable equals undefined, and undefined += number (for example 25) returns NaN;

也改变; 在此行

来自

for (var i = 0, i < array.length; i++) {

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

这篇关于数组中对象属性的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆