为什么不能从多个文件推送文本(使用html5文件阅读器上传)返回数组

时间:2013-12-13 09:45:44

标签: javascript html5 filereader

我正在尝试使用html 5文件阅读器上传两个文本文件。我可以将文件放到数组中,但是无法从函数中返回数组。我想我可以将它们推入全局数组并使用它。然而,我提出这个问题的主要原因是要了解为什么回报不起作用,因为这里显然有一些我不理解的东西。

function processFiles(files) {
    console.log(getEmails(files));   //this statement should log textArray to console, but returns undefined instead
    function getEmails(files){
        var textArray = [];

        for(var i=0; i<files.length; i++){
            (function(files,i){

                var file = files[i];
                var reader = new FileReader();

                reader.onload = function (e) {
                    textArray.push(e.target.result);
                    if (i==(files.length-1))
                    {
                        console.log(textArray); //this logs test array to the console no probs
                        return textArray;// so why wont this return text array so the previous console.log works
                    }
                };  
                reader.readAsText(file,"Unicode");  
            })(files,i);

        }
    } 
}


<input id="fileInput" type="file" onchange="processFiles(this.files)" multiple>

1 个答案:

答案 0 :(得分:0)

设置reader.onload时,如果没有调用该函数,则表示加载文件时要调用的函数。这将在未来的某个时刻发生,而不是在getEmails函数的上下文中。这称为异步函数。

您无法在processFiles中记录这些文件(如果要在加载时记录这些文件)。你需要为每个&#34; onload&#34;将构建textArray的事件(通常应该是一个全局变量),知道何时总共有&#34; i&#34;文件已加载(同样,应该全局跟踪;并注意您不知道这将发生的顺序),然​​后记录结果。

(我也不确定为什么,在循环中,你将功能包装在另一个函数中。这些东西都可以在循环中内联。)

您可能希望阅读异步处理,以更清楚地了解正在进行的操作。