如何在多个Firebase子节点上平均投票?

问题描述:

这个问题has been asked before但我不太明白答案。如何在多个Firebase子节点上平均投票?

我需要计算来自Firebase的数据数组的平均值,所以我有两个步骤。

  1. 检索的所有数据
  2. 确定使用多少条目中有相同的数据
  3. 计算平均

我的代码:

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查询中的数据“取出”并转换为函数。我错过了什么?

+0

带来的函数调用步入回调,这就是数据,你需要的生活。 – dandavis

+0

@dandavis但有两个回调,我该如何处理? –

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事件。不知道你为什么同时使用valuechild_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); 
}); 

我正在做同样的事情,你正在尝试做,但与用户的评级。我为您更改了“评分”这个词,并添加了“myDataRef”。这为我工作:

控制器:

myDataRef.getVotesforUser(uid).then(function(votes) { 

for(var i = 0; i < votes.length; i++) { 
    votes[i].type? $scope.userVote.push(votes[i]) : $scope.userVote.push(votes[i]) 
} 

$scope.numVote = $scope.userVote.length; 


$scope.total = 0; 
votes.forEach(function(votes) { 
    $scope.total += votes.vote; 
}); 
console.log("average", + $scope.total); 
console.log("average", + $scope.total/$scope.numVote); 

});

服务:

getVotesforUser: function(uid) { 
    var defer = $q.defer(); 

    $firebaseArray(ref.child('user_votes').child(uid)) 
     .$loaded() 
     .then(function(votes) { 
     defer.resolve(votes); 
     }, function(err) { 
     defer.reject(); 
     }); 


    return defer.promise; 
    },