Array.push不更新数组变量

时间:2015-06-03 19:43:49

标签: javascript arrays

以下是我正在处理的代码:

<!--HTML Code for referencing the file -->
<input type="file" name="file" id="file">
<script>
var store = [];
document.getElementById('file').onchange = function(){
    var file = this.files[0];
    var reader = new FileReader();

    // Define the body of reader function
    reader.onload = function(progressEvent){

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){

    // Store it in an array
    store.push(lines[line]);
    //console.log(store.length); // This line on being uncommented
    // shows that store is being modified. The values getting printed
    // are 1,2,3, ...... upto 16 (length of the input file)
}
};

// Read the file and store it in the var "store"
reader.readAsText(file);
console.log(store.length); // The problem appears here!!!!!
};
</script>

问题是,即使在选择包含16个样本编号的文件后,控制台也会将store.length值打印为0.为什么push命令不会影响var“store”?

3 个答案:

答案 0 :(得分:1)

你正在onchange属性上设置一个事件处理程序,但你在外面做一个console.log(store.length),所以你永远不会得到你期望的结果。

当id为“file”的元素的值发生变化时,将触发事件处理函数,因此您需要在函数内打印商店的长度,如下所示:

document.getElementById('file').onchange = function(){
    var file = this.files[0];
    var reader = new FileReader();

    // Define the body of reader function
    reader.onload = function(progressEvent){

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){

    // Store it in an array
    store.push(lines[line]);
    //console.log(store[line]);

     }
    console.log(store.length);
};

我建议将该商店声明为该功能的本地存储,这样您将始终获得一个全新的数组,否则您需要手动重新初始化它或在开始向其添加内容之前将其清空更改事件,您的“商店”数组将填充先前更改的所有内容。

有道理吗?

答案 1 :(得分:0)

onload的{​​{1}}事件是异常的。这意味着它不会在程序的自然流程中执行。

要检查FileReader变量的最终长度,您应该这样做:

store

希望它有所帮助。

答案 2 :(得分:0)

FileReader是异步的。您要么使用FileReaderSync,要么执行此操作:

&#13;
&#13;
var store = [];
document.getElementById('file').onchange = function() {
  var file = this.files[0];
  var reader = new FileReader();

  // Define the body of reader function
  reader.onload = function(progressEvent) {

    // By lines
    var lines = this.result.split('\n');
    for (var line = 0; line < lines.length; line++) {

      // Store it in an array
      store.push(lines[line]);
    }
  };

  reader.onloadend = function() {
    console.log(store.length);
  };

  // Read the file and store it in the var "store"
  reader.readAsText(file);
};
&#13;
<input type="file" name="file" id="file">
&#13;
&#13;
&#13;