我正在检查firebase文档,寻找如何根据查询获取保存在我的DB中的条目的数量,我查看了这段代码,这些代码具有(我认为)我想要的内容,但不知道如何获得显示的项目数。
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.orderByChild("height").equalTo(0.6).on("child_added", function(snapshot) {
console.log(snapshot.key());
});console.log应该显示两个项目,因为有两个恐龙具有这个高度。那么,我如何才能获得显示在视图中的项目数呢?
我尝试过使用console.log(snapshot.key().length);但是它显示了一个错误的号码
发布于 2015-11-24 23:24:56
当您侦听child_added事件时,回调中的项目数将始终是1。当您(例如)想要将每一项添加到列表中时,这是很好的。但是当你想数数物品的数量时,这并不是很好。
对于需要处理多个项的操作,更容易侦听value事件:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.orderByChild("height").equalTo(0.6).on("value", function(snapshot) {
console.log(snapshot.numChildren());
})这个片段还显示了拼图的另一部分:DataSnapshot.numChildren()。
发布于 2015-11-24 21:13:17
你可以试试这个:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
var shortDinosaurs = ref.orderByChild("height").equalTo(0.6);
console.log(shortDinosaurs.length);
shortDinosaurs.on("child_added", function(snapshot) {
console.log(snapshot.key());
});https://stackoverflow.com/questions/33903640
复制相似问题