使用Firebase数组值更新全局Javascript变量

时间:2016-03-13 00:03:13

标签: javascript arrays firebase global-variables updating

我正在尝试在checkAndPush函数中使用Firebase数组值(array1),但控制台表示在firebaseArrayValFunction外部调用时数组未定义。关于如何解决这个问题或为什么会这样做的任何想法?

谢谢你看看。

$(document).ready(function(){     console.log("准备就绪!");

var myFirebaseRef =新的Firebase(" https://firebaseio.com/");

myFirebaseRef.set({

     quote: ["  Quote 1","Quote 2","Quote 3"]

});

    var array2 = [];
    var array1 = [];
    var array1Random;
    var array2Random;




var firebaseArrayValFunction = myFirebaseRef.child("quote").on("value", function(snapshot) {
        var array1 = snapshot.val();
        var array1Random = array1[Math.floor(Math.random()*array1.length)];
           console.log(array1);
           console.log(array1Random);
   });


 var restart = setTimeout(checkAndPush, 1000);




function checkAndPush() {


    //This if statement should say array.length === 0 but that will run infinitely at the moment because array1.length is undefined so 6 is there to keep //the function from immediately calling checkAndPush2
    if (array1.length === 6) {
             console.log("ARRAYS ARE EQUAL");
                checkAndPush2();
                 return false; 

       }else if(jQuery.inArray(array1Random, array2) !== -1){
            console.log("its there");
            setTimeout(checkAndPush, 5000);

       } else {
               array2.push(array1Random);

               var index = array1.indexOf(array1Random);
               array1.splice(index,1);
               console.log(array1);
               console.log(array2);
               setTimeout(checkAndPush, 5000);
               }
         }





function checkAndPush2() {
    var array2Random = array2[Math.floor(Math.random()*array2.length)];

    if (array2.length === 0) {
             console.log("ARRAYS ARE EQUAL");
                checkAndPush();
                return false;
         }

    else if(jQuery.inArray(array2Random, array1) !== -1){
        console.log("its there");
        setTimeout(checkAndPush2, 5000);

    }

    else{

               array1.push(array2Random);

               var index = array2.indexOf(array2Random);
               array2.splice(index,1);
               console.log(array1);
               console.log(array2);
               setTimeout(checkAndPush2, 5000);
               }

}

});

0 个答案:

没有答案