Javascript全局数组访问成员未定义

时间:2014-09-27 21:21:28

标签: javascript arrays scope

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.

上面的代码显示了一个Js,它将文件转换为在按钮事件之后运行的二进制字符串,并且我遇到了无法访问使用filereader onload事件中新推送的值更新的全局变量arrayTest的问题.Is无论如何要解决这个问题?

1 个答案:

答案 0 :(得分:0)

确定。我意识到当我醒来时执行console.log时,异步任务可能仍然在运行,这意味着arrayTest不完整,所以我这就是我为解决这个问题所采取的措施。

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);
}