我有一系列功能,我想按属性找到平均值
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 个问题。
for each
在 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)
)