gpt4 book ai didi

javascript - Array.push 不更新数组变量

转载 作者:行者123 更新时间:2023-12-03 09:59:55 25 4
gpt4 key购买 nike

这是我正在处理的代码:

<!--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”?

最佳答案

您正在 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);
};

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

有道理吗?

关于javascript - Array.push 不更新数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com