未定义的数组
问题描述:
public onChange(event: Event) {
let files = event.target['files'];
let list: string[];
console.log(files);
for (var i = 0; i < files.length; i++) {
if (FileReader && files && files.length) {
let fileReader = new FileReader();
fileReader.onload = () => {
let infoFile: string = fileReader.result;
list.push(infoFile);
};
fileReader.readAsDataURL(files[i]);
}
}
console.log(list);
let preview = document.querySelector('img');
preview.src = list[0];
};
我在我的component.ts中有方法,当我点击input type =file时,名为medthod onChange )但是当在控制台中留下循环时,我有消息该数组是未定义的。我检查fileReader.result不是空的为什么发生这种情况?如何解决这个问题的一些想法。
I have method in my component.ts when i click input type="file" called medthod onChange() but when left loop for in console i have message that array is undefined. I check that fileReader.result is not empty Why is this happening? How to solve this problem some idea.
答
您必须先初始化列表:
let list: string[] = [];
当你做的时候
when you do just
let list: string[]
你只告诉编译器这个变量将是一串字符串。但是在运行时它是不确定的,因为你还没有初始化它。
you only tell the compiler that this variable will be an array of strings. But at runtime it is undefined, because you didn't initialized it anyway.