Skip to main content
 首页 » 编程设计

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

2025年12月25日34jiqing9006

在我的应用程序中的单击事件中,我返回 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); 

请您参考如下方法:

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);


如果你想使用 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);