这个问题has been asked before但我不太明白答案。
我需要计算 Firebase 中数据数组的平均值,因此有两个步骤。
- 检索所有数据
- 确定同一数据中有多少条目
- 计算平均值
我的代码:
myDataRef.orderByChild("time").startAt(time-180000).endAt(time).on("child_added", function(snapshot) {
votes = snapshot.val().vote;
//console.log("Vote value:" + votes)
});
myDataRef.orderByChild("time").startAt(time-180000).endAt(time).on("value", function(snapshot) {
numberOfVotes = snapshot.numChildren();
//console.log("Number of Votes:" + numberOfVotes)
});
function calculateAverage(numberOfVotes, votes) {
return eval(votes.join('+')) / numberOfVotes;
}
console.log(calculateAverage)
我认为我误解了一些非常基本的东西,因为我无法弄清楚如何将数据从 Firebase 查询“取出”并放入函数中。我错过了什么?
最佳答案
Firebase 异步加载数据。只有在查询数据完全加载后,您才能确定平均值。
我想到的一种方法是:
myDataRef.orderByChild("time").startAt(time-180000).endAt(time).on("value", function(snapshot) {
var voteCount = snapshot.numChildren();
var total = 0;
snapshot.forEach(function(voteSnapshot) {
total += voteSnapshot.val().vote;
});
console.log("Average=" + total / voteCount);
});
一些值得注意的事情:
- 我使用单个
value
事件。不知道为什么您同时使用value
和child_added
,但这似乎只会让事情变得复杂。
也可以在监听 child_
事件时保持运行平均值,但您必须监听所有事件。
var total = 0,
voteCount = 0;
query = myDataRef.orderByChild("time").startAt(time-180000).endAt(time);
query.on("child_added", function(snapshot) {
voteCount += 1;
total += snapshot.val().vote;
console.log("Running average: "+total/voteCount);
});
query.on("child_removed", function(snapshot) {
voteCount -= 1;
total -= snapshot.val().vote;
console.log("Running average: "+total/voteCount);
});
关于javascript - 如何对多个 Firebase 子节点进行平均投票?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495398/