未定义的数组 [英] Undefined Array

查看:129
本文介绍了未定义的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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.

这篇关于未定义的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆