如何从Firebase检索数据然后推入多维数组

时间:2019-04-20 11:12:49

标签: javascript arrays firebase multidimensional-array firebase-realtime-database

//Configure the Firebase (credential information removed)
    var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "731787069959"
      };

//Initialize the firebase and reference to the root
  firebase.initializeApp(config);
  var ref =  firebase.database().ref('online_class_test_result/student');

//declare array
var student_result = new Array();

//Snapshot all the data in the ref
ref.on('value', function(snapshot) {
    //loop all the data in the Firebase reference and stored in array
    for (var i = 0; i < snapshot.numChildren(); i++) {

      var key = Object.keys(snapshot.val())[i];
      var student_name = (snapshot.val()[key]['student_name']);
      var score = (snapshot.val()[key]['score']);

      console.log(student_name); //data get successfully
      console.log(score); //data get successfully

      //stored in multidimensional array
      student_result[i] = ([student_name,score]);
    }
  });

当我进行控制台登录时,记录student_result。它可以将数据显示为 如下所示:

console.log(student_result);
result:
[ ]
0: Array [ "Wei Kang", 100 ]
1: Array [ "test", 50 ]
length: 2

但是,当我要检查student_result数组中的第一个元素时,它显示为undefined:

console.log(student_result [0]);
result: undefined

当console.log(student_result [0])如下时,我的预期结果是:

result:
Array [ "Wei Kang", 100 ]

任何人都可以找出我的问题吗?预先感谢。

0 个答案:

没有答案