Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript读取多个文件只会导致读取最后一个文件_Javascript_File_Io_Filereader - Fatal编程技术网

使用Javascript读取多个文件只会导致读取最后一个文件

使用Javascript读取多个文件只会导致读取最后一个文件,javascript,file,io,filereader,Javascript,File,Io,Filereader,我必须在JavaScript代码中读入一些测试文本文件。有三个文件,分别名为1.txt、2.txt和3.txt,每个文件都包含一行。我写了这段代码,我认为它可以很好地工作: function handleFileSelect(evt) { var files = evt.target.files; // FileList object for (var i = 0; i < files.length; i++) { console.log("Start lo

我必须在JavaScript代码中读入一些测试文本文件。有三个文件,分别名为
1.txt
2.txt
3.txt
,每个文件都包含一行。我写了这段代码,我认为它可以很好地工作:

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        console.log("Start loop")
        myFile = files.item(i);
        var myReader = new FileReader();
        myReader.readAsText(myFile);
        myReader.onload = function(e) {
            var rawLog = myReader.result;
            console.log(rawLog)
        };

    }
};

document.getElementById('files').addEventListener('change', handleFileSelect, false);
但它的输出如下:

Start loop
Contents 1.txt
Start loop
Contents 2.txt
Start loop
Contents 3.txt
Start loop 
Start loop
Start loop
null
null
Contents 3.txt

如何生成第一个?我希望错误出现在onload函数中,但我不确定我做错了什么…

在您的代码中
var myReader=new FileReader()
在每个循环中重新分配变量,从而销毁第一个实例

我建议您将代码拆分为两个函数,以防止本地块变量的实例在完成之前被覆盖

function readFile(file) {
    var myReader = new FileReader();
  myReader.readAsText(file);
  myReader.onload = function(e) {
      var rawLog = myReader.result;
      console.log(rawLog)
  };
} 

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        myFile = files.item(i);
        readFile(myFile);
    }
};
函数readFile(文件){
var myReader=newfilereader();
myReader.readAsText(文件);
myReader.onload=函数(e){
var rawLog=myReader.result;
console.log(rawLog)
};
} 
功能手柄文件选择(evt){
var files=evt.target.files;//文件列表对象
对于(var i=0;i