1
//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]);
    }
  });

When I console log the student_result. it can show the data inside as shown below:

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

However, when I want to check the first element in the student_result array, it show undefined:

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

My expected result when console.log(student_result [0]) is as shown below:

result:
Array [ "Wei Kang", 100 ]

Anyone can figure out my problem ? Thanks in advance.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Wei Kang
  • 163
  • 2
  • 9
  • 1
    Are you accessing `student_result[0]` outside of `ref.on('value', function(snapshot) {..})`? Because that looks like an asynchronous callback – adiga Apr 20 '19 at 11:28
  • Hi adiga, Yes, I console.log(student_result[0]) outside of the ref.on('value', function(snapshot). Because I thought I was able to access all the items in the multidimensional array outside the loop. – Wei Kang Apr 20 '19 at 12:04
  • Hello adiga, I am sorry to tell you that I am new to Firebase. But your comment about the asynchronous callback help me to solve my problem. I should not execute anything outside the loop. Thanks you very much. – Wei Kang Apr 20 '19 at 12:23

0 Answers0