迭代和修改Firebase数组会导致未定义

Iterating and modifying Firebase array causes undefined

本文关键字:未定义 数组 修改 Firebase 迭代      更新时间:2023-09-26

EDIT:似乎值[i].extrainfoimage仅在imageRef.child("-JlSvEAw…

到目前为止,我已经阅读了两次文档,但仍然无法理解这一点。

基本上,我从firebase加载一些数据,并将其设置为数组。我遍历该数组,并打算在迭代时用从Firebase DB中其他位置获得的数据替换一些属性。然而,每次我去更换属性时,我都会得到

"未捕获的类型错误:无法设置未定义"的属性"extrainfoimage"

这是我的代码:

var questionsRef = new Firebase("https://XX.firebaseio.com/Questions");
var imageRef = new Firebase("https://XX.firebaseio.com/Images");
//get the first 6 items
var query = questionsRef.orderByChild('date_time_asked').limitToFirst(6);
//get them as a firebase array promise
$scope.questions = $firebaseArray(query);
//wait for it to load
$scope.questions.$loaded().then(function (value) {
//iterate through
for (i = 0; i < value.length; i++) {
    //check if there is data to be replaced
    if (value[i].extrainfoimage) {
           //if there is fetch it from firebase and replace
           imageRef.child("-JlSvEAwu5-WZJkOE_b/image").once("value",function(data){
                        value[i].extrainfoimage = data.val();
                    });
                }
            }
        })

可能是因为值中的最后一项没有extrainfoimage。因为value[i].extrainfoimage的集合是异步的,所以它不会捕获正确的i值,因此在执行时会失败。

尝试将其封装在IIFE:中

for (i = 0; i < value.length; i++) {
    //check if there is data to be replaced
    if (value[i].extrainfoimage) {
       (function(curr) {
           //if there is fetch it from firebase and replace
           imageRef.child("-JlSvEAwu5-WZJkOE_b/image").once("value",function(data){
                    value[curr].extrainfoimage = data.val();
           });
        })(i);
    }
}