我正在查看 firebase 文档,寻找如何根据查询获取保存在我的数据库中的项目数量,我查看了这段代码,它(我认为)正是我正在寻找的,但不知道如何获取显示的项目数。
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 应显示 2 项,因为有 2 只恐龙具有该高度。那么我怎样才能获得显示的项目数以显示在 View 上呢?
我尝试使用 console.log(snapshot.key().length);但它显示错误的数字
最佳答案
当您监听 child_added
事件时,回调中的项目数将始终为 1
。当您(例如)想要将每个项目添加到列表时,这非常有用。但是当你想计算项目的数量时,它就不太好了。
对于需要处理多个item的操作,监听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()
。
关于javascript - 获取 orderByChild equalTo 中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33903640/