我正在尝试使用页面加载时生成的快照从我的 Firebase 数据库中获取一组项目。我已经将每个对象的值添加到一个数组中,现在我正尝试使用 for 循环将每个对象中的一个项目推送到另一个数组中。
但是当我创建第二个数组时,其中的项目比快照中的对象多。
我想知道如何解决这个问题。任何帮助都是极好的。谢谢。
代码:
var ref = firebase.database().ref().child('/scenes/' + projId).orderByChild('wordcount');
ref.once('value',function(snap) {
snap.forEach(function(item) {
var itemVal = item.val();
keys.push(itemVal);
for (i=0; i < keys.length; i++) {
counts.push(keys[i].wordcount);
}
});
});
最佳答案
每次您向键添加内容时,您都会再次遍历它们。你应该把它移到你的 forEach 之外:
var ref = firebase.database().ref().child('/scenes/' + projId).orderByChild('wordcount');
ref.once('value',function(snap) {
snap.forEach(function(item) {
var itemVal = item.val();
keys.push(itemVal);
});
for (i=0; i < keys.length; i++) {
counts.push(keys[i].wordcount);
}
});
关于javascript - 从 Firebase 快照中获取项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41427859/