javascript对象中特定属性的总和值

the*_*ide 2 javascript foreach

在我的应用程序中的单击事件中,我返回highlights- 一系列功能(每次都有不同的长度).所以console.log(highlights)产生:

在此输入图像描述

我的目标是返回properties.census2010_Pop2010对象中每个要素所包含的值的总和.到目前为止,我已经尝试了下面的代码,但控制台中没有返回任何内容.任何建议,将不胜感激.

total = Object.create(null);

highlights.feature.properties.forEach(function (a) {
    a.census2010_Pop2010.forEach(function (b) {
        total = total + b.census2010_Pop2010;
    });
});

console.log(total);
Run Code Online (Sandbox Code Playgroud)

epa*_*llo 6

highlights 是一个数组,你应该循环.

var highlights = [
  {properties : { census2010_Pop2010: 10}},
  {properties : { census2010_Pop2010: 20}},
  {properties : { census2010_Pop2010: 30}}
]

var total = highlights.reduce( function(tot, record) {
    return tot + record.properties.census2010_Pop2010;
},0);


console.log(total);
Run Code Online (Sandbox Code Playgroud)

如果你想使用forEach,它将是这样的:

var highlights = [
  {properties : { census2010_Pop2010: 10}},
  {properties : { census2010_Pop2010: 20}},
  {properties : { census2010_Pop2010: 30}}
]

var total = 0;
highlights.forEach( function(record) {
    total += record.properties.census2010_Pop2010;
});


console.log(total);
Run Code Online (Sandbox Code Playgroud)