javascript - For循环取javascript中对象属性的平均值

标签 javascript arrays loops mapbox

我有一系列特征,我想找到属性的平均值

var features = map.queryRenderedFeatures({ layers: ['my_layer']});
console.log(features)

返回:

(10) [Feature, Feature, Feature, Feature, Feature, Feature, Feature, Feature, Feature, Feature]
0:Feature
layer:{id: "my_layer", type: "circle", source: "tbr", filter: Array(3), layout: {…}, …}
properties:{bikeid: 15847, diff.time: 2.25, …}

但是,当我尝试获取每个功能的 diff.time 属性的总和和长度时,会返回一个语法错误,并带有意外的标识符。

var sum = 0 
var length = 0    

    for each (var feature in features) {
    sum += feature.properties['diff.time'];
    length ++

    }

    console.log(sum/length)


Uncaught SyntaxError: Unexpected identifier

此语法有何错误?应更改哪些内容才能获得所需的结果?

最佳答案

我发现您的代码有 3 个问题。

foreach 不是 javascript 中的有效循环,但是 Array#forEach 是数组上的一个方法。

当您执行 for in 时,您应该迭代对象键,它仍然可以工作,但您将循环遍历 length 属性,并且在迭代数组时效率不高,所以在这种情况下,您应该执行 for 循环并迭代数组的索引。

最后一个问题是,在合法的情况下命名属性 diff.time 并不是命名属性的好方法,因为您将无法使用点运算符访问它。

var sum = 0
var length = 0

for(var i; i < features.length; i+=1) {
  sum += features[i].properties['diff.time']; // don't think diff.time will work
  length++
}

console.log(sum / length)

除此之外,JavaScript 有一种更好、更明确的方法来使用 Array#reduce 将值数组更改为单个值。

class Feature {
  constructor(id) {
    this.id = id
    this.properties = {
      'diff.time': 2.25 // this is a not a good way to name a property
    }
  }
}

const features = [
  new Feature(1),
  new Feature(2),
  new Feature(3),
]

console.log(
  features.reduce((acc, x) => {
    return acc + x.properties['diff.time']
  }, 0)
)

关于javascript - For循环取javascript中对象属性的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47377666/

相关文章:

MySQL 中的 Javascript 数组

c# - 将类转换为数组

r - 对于线性模型,有没有办法遍历 r 中的列名(不是数字)?

python - 如何在 python 上循环而不出现 IndexError ?

javascript - 获取对象内数组中的总对象数

javascript - 响应式菜单的子菜单在离开屏幕时不会强制滚动

javascript - 我的数组输出中的 `#` 来自哪里?

javascript - 有没有办法在 JQuery 和 AngularJS 中用 touchend 监听器替换所有点击监听器?

ruby - Ruby 中有 "do ... while"循环吗?

javascript - 在 devbridge 自动完成插件中传递 ajax 调用的数据参数