Javascript 推送到对象内部的数组

Javascript 推送到对象内部的数组,javascript,Javascript,我最近刚学了JS,一直在做一个练习,将人们从一系列记录中,祖先,分类到他们生活的世纪和年龄。下面是来自祖先的示例元素: { name: "Carolus Haverbeke" sex: "m" born: 1832 died: 1905 father: "Carel Haverbeke" mother: "Maria van Brussel" } 以下是我的尝试: ancestry.forEach(function(person) { var ages = {}; v

我最近刚学了JS,一直在做一个练习,将人们从一系列记录中,
祖先
,分类到他们生活的世纪和年龄。下面是来自
祖先
的示例元素:

{
name:   "Carolus Haverbeke"
sex:    "m"
born:   1832
died:   1905
father: "Carel Haverbeke"
mother: "Maria van Brussel"
}
以下是我的尝试:

ancestry.forEach(function(person) {
  var ages = {};
  var century = Math.ceil(person.died / 100);

  if (century in ages) 
    ages[century].push(person.died - person.born);
  else
    ages[century] = person.died - person.born;
});
这是我试图存储在
年龄
中的通用格式,它将每个世纪映射到一系列人的年龄:

{
16: [24, 51, 16]
17: [73, 22]
18: [54, 65, 28]
}
我真的很困惑,因为这个代码只将
祖先中的第一个人保存到
年龄中。我想这可能是因为我在
forEach
中定义了
ages
,但当我将
var ages={}
移到外部时,我得到了以下结果:

TypeError:ages[century]。推送不是一个函数(第18行)


有人能解释一下发生了什么,代码应该被修复吗?

你需要在else语句中创建数组,比如
ages[century]=[person.died-person.born]

    ancestry.forEach(function(person) {
      var ages = {};
      var century = Math.ceil(person.died / 100);

      if (century in ages) 
        {
        ages[century].push(person.died - person.born);
            }
      else
           {       
        ages[century] = [person.died - person.born];
           }
    });
tl;博士


我们将描述您的代码以了解问题:

假设我们有一个
祖先
数组(这意味着
var祖先=[{…},{…},…]
是这种形式,每个项看起来如下所示:

var ancestry = [{
    name: "Carolus Haverbeke",
    sex:  "m",
    born: 1832,
    died: 1905,
    father: "Carel Haverbeke",
    mother: "Maria van Brussel"
}, {
    name: "Carolus Haverbeke",
    sex:  "m",
    born: 1722,
    died: 1805,
    father: "Carel Haverbeke",
    mother: "Maria van Brussel"
}, {
    name: "Carolus Haverbeke",
    sex:  "m",
    born: 1666,
    died: 1705,
    father: "Carel Haverbeke",
    mother: "Maria van Brussel"
}, {
    name: "Carolus Haverbeke",
    sex:  "m",
    born: 1622,
    died: 1715,
    father: "Carel Haverbeke",
    mother: "Maria van Brussel"
}];
使用不同的数据

要实现您的目标,请执行以下步骤:

// Create your variable in the parent scope to allow variables to exist after the end of `forEach` method.
var ages = {};

// In the ancestry Array, we will loop on all items like `{ ... }`.
ancestry.forEach(function (person) {
  // For each loop `person` will contain the current `{ ... }` item.

  // Because we want add this property to the existant object, we don't need a new object. And as you said,
  // 1. `ages` will be deleted in each loop because is defined into `forEach`
  // var ages = {};

      // We get the century of die.
  var century = Math.ceil(person.died / 100),
      // and age of die
      age = person.died - person.born;

  // now if the century property not exist, create a new array into to accept all centuries after.
  if (!ages[century]) {
      ages[century] = [];
  }
  // equivalent to `!ages[century] && (ages[century] = []);`

    // in all cases, just push the value to the end.
    ages[century].push(age);
});

// Still exist !
console.log(ages); // Object {18: Array(2), 19: Array(1), 20: Array(1)}
您的最终格式是您想要的:

{
    18: [39, 93],
    19: [83],
    20: [73]
}

您需要在外部定义
age
数组

您收到的错误是因为您没有将
age[century]
初始化为
数组
。因此它只存储一个值

添加这一行

ages[century] = []
ages[century].push()
那时就可以了

以下是您需要在
if else

if (ages[century]){
   ages[century].push(person.died - person.born);
}
else{
   ages[century] = []
   ages[century].push(person.died - person.born);
}

您需要将
century
变量实例化为键值对中的键(一种称为“关联数组”的数组类型),然后将
age
存储到该数组中的另一个数组中(请记住
century
是您的键,值是数组)

基本上,它是一个二维关联数组,因此您可以只使用一个对象。

所以它需要看起来像
varages={16:{24,51,16},17:{73,22},18:{54,65,28};

var ages={16:{},17:{},18:{};
然后可以递归地将这些值推送到相应键的数组中

键值对:

多维关联数组(对象):

W3School(JavaScript对象):

您可以将年龄数组存储在一个对象中,并通过键访问该数组(在您的示例中,您已声明为
century

如果是我,我会将
作为一个对象,然后将每个人的
生日
死亡日期
死亡年龄
作为属性存储在数据库中


出于好奇,当一个人生活在两个不同的世纪时,你会怎么做?我出生于1987年,现在是2017年,那么我是生活在20世纪还是21世纪?

我试图保存一系列的年龄-你的代码意味着年龄在每一个世纪发生时都会被覆盖。
if (ages[century]){
   ages[century].push(person.died - person.born);
}
else{
   ages[century] = []
   ages[century].push(person.died - person.born);
}