简体   繁体   中英

Javascript global array accessing member undefined

var arrayTest;

function handleFiles(files) {
   arrayTest = new Array();
   for(var i = 0; files[i]; i++) {
       var reader = new FileReader();
       reader.onload = function(e) {
          var binary = e.target.result;
          var parentSelector = '#output_' + i;
          $(parentSelector).html(binary);
          arraytest.push({ 'bin' : binary, 'parentSelector' : parentSelector });
       };
       reader.readAsBinaryString(files[i]);
   }
}

function buttonClick() {
    var files = [file1, file2];
    handleFiles(files);
    console.log(arrayTest); // I got the objects inserted at async function here, length != 0
    console.log(arrayTest.length); // 0
    console.log(arrayTest[0]); //undefined
    // accesing any member of arrayTest returns undefined
}

FireFox Console output.

The code above shows a Js that converts files into binary string that is ran after a button event and I am having issues with being unable to access the global variable arrayTest that is updated with newly pushed value from the filereader onload event.Is there anyway to fix this problem?

Ok. I realized when I woke up that the point where console.log is executed, the async task might still be running which means that the arrayTest is incomplete, so what I this is what I did to fix the issue.

var arrayTest;
var asyncCount;

function handleFiles(files) {
   arrayTest = new Array();
   asyncCount = 0;
   for(var i = 0; files[i]; i++) {
       var reader = new FileReader();
       asyncCount += 1;
       reader.onload = function(e) {
          var binary = e.target.result;
          var parentSelector = '#output_' + i;
          $(parentSelector).html(binary);
          arrayTest.push({ 'bin' : binary, 'parentSelector' : parentSelector });
          asyncCount -= 1;
          if(asyncCount === 0) {
             console.log(arrayTest); 
             console.log(arrayTest.length);
             console.log(arrayTest[0]); 
             // at this point I am able to access all the array members.
          }
       };
       reader.readAsBinaryString(files[i]);
   }
}

function buttonClick() {
    var files = [file1, file2];
    handleFiles(files);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM