在.on方法完成后,如何在我的firebase中循环所有项目并递增所有值后,如何打印“obj”值?简而言之,我在这里要做的是,一旦循环完成,我想将结果(“obj”)打印到控制台。
在此欣赏任何帮助!感谢。
var obj = {
"20120101" : {"neutral": 0, "positive": 1, "negative": 2},
"20120101" : {"neutral": 0, "positive": 1, "negative": 2}
} //above is just an example on the structure of the object
var fbase = new Firebase("https://<appname>.firebaseio.com/");
fbase.on('child_added', function(snapshot){
var item = snapshot.val(); //has the attributes of: date & classification
var date_str = item.date;
if (!obj[date_str]){
//initialise the counting;
obj[date_str] = { "negative": 0, "neutral": 0, "positive" : 0 };
}
obj[date_str][item.classification] += 1;
});
console.log(obj);
答案 0 :(得分:1)
在咨询Firebase文档后,我终于找到了我的问题的答案: https://www.firebase.com/docs/javascript/datasnapshot/index.html
以下是我更新的代码,以防有人遇到同样的问题:
var obj = {
"20120101" : {"neutral": 0, "positive": 1, "negative": 2},
"20120101" : {"neutral": 0, "positive": 1, "negative": 2}
} //above is just an example on the structure of the object
var fbase = new Firebase("https://<appname>.firebaseio.com/");
fbase.once('value', function(allMessagesSnapshot) {
allMessagesSnapshot.forEach(function(messageSnapshot) {
var date = messageSnapshot.child('date').val();
var classification = messageSnapshot.child('classification').val();
// Do something with message.
if (!obj[date]){
obj[date] = { "negative": 0, "neutral": 0, "positive" : 0 };
}
obj[date][classification] += 1;
});
console.log(obj);
});
感谢您的回答,感激不尽! :d
答案 1 :(得分:0)
你必须把它放在回调中:
var obj = {
"20120101" : {"neutral": 0, "positive": 1, "negative": 2},
"20120101" : {"neutral": 0, "positive": 1, "negative": 2}
} //above is just an example on the structure of the object
var fbase = new Firebase("https://<appname>.firebaseio.com/");
fbase.on('child_added', function(snapshot){
var item = snapshot.val(); //has the attributes of: date & classification
var date_str = item.date;
if (!obj[date_str]){
//initialise the counting;
obj[date_str] = { "negative": 0, "neutral": 0, "positive" : 0 };
}
obj[date_str][item.classification] += 1;
console.log(obj);
});
因为回调是在将来的某个时间调用的,所以数据唯一可用的位置是回调内或可以从回调中调用的任何函数。