如何将函数输出传递到函数主体之外?

时间:2019-02-25 15:37:22

标签: javascript json

我正在尝试使用本文中的代码读取多个JSON文件:

Reading multiple files with Javascript FileReader API one at a time

两个JSON文件Nathan.jsonCharles.json的内容为:

{"name": Nathan, "age": 24,"title": "Product Consultant"}
{"name": Charles, "age": 31, "title": "software engineer"}

我定义了一个全局变量myOutput来存储输出,但是不会将其传递到函数外部。为了演示我首先在函数中登录myOutput

<html>

<head>
<title>
This is the JSON test.
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <input type="file" id="filesx" name="filesx[]" onchange="readmultifiles(this.files)" multiple=""/>
    <div id="bag"><ul/></div>
    <script>
    // define the global variable to store the function output
    var myOutput = [];
    window.onload = function() 
    {
        if (typeof window.FileReader !== 'function') 
      {
        alert("The file API isn't supported on this browser yet.");
      }
    }

    function readmultifiles(files) {
        var ul = document.querySelector("#bag>ul");

        while (ul.hasChildNodes()) {
            ul.removeChild(ul.firstChild);

        }

        function setup_reader(file) 
        {
            // name of the file, nothing to do with its actual content
          var name = file.name;
          var reader = new FileReader();
          reader.onload = function(e) 
          {
            var bin = e.target.result; //get file content
            // push the content into the global variable
            myOutput.push(bin);

            // create the text displayed after uploading the files
            var li = document.createElement("li");
            li.innerHTML = name + '<br />' + bin;
            ul.appendChild(li);
            console.log(myOutput);
          }
          reader.readAsBinaryString(file);
        }
        for (var i = 0; i < files.length; i++) 
        { 
            setup_reader(files[i]); 
        }
    }        
    </script>
    </body>

    </html>

它正常工作并记录下来:

enter image description here

但是如果我将日志移到函数之外:

    ......
       ul.appendChild(li);
       }
     reader.readAsBinaryString(file);
     console.log(myOutput);
    }
    for (var i = 0; i < files.length; i++) 
    { 
     setup_reader(files[i]); 
    }
}        
</script>
......

日志信息变为:

enter image description here

为什么会发生这种情况,如何在函数外部传递变量?

谢谢!

0 个答案:

没有答案