【问题标题】:For In loop with Filelist returns the wrong type带有 Filelist 的 For In 循环返回错误的类型
【发布时间】:2018-08-02 08:00:51
【问题描述】:

我想使用 Typescript 循环通过 for in 循环的 FileList。 我从一个常规的旧 for 循环开始,这非常有效:

let files:FileList = e.target.files
for(let i = 0;i<files.length;i++){
  doSomething(files[i])
}

function doSomething(f:File){
}

但是当我使用较短的for..in 循环时:

for(let f in files){
   doSomething(f) 
}

我收到一个错误:Argument of type 'string' is not assignable to parameter of type 'File'。所以f 在某种程度上被认为是一个字符串,即使 FileList 包含文件,而不是字符串。

这些修复不起作用:

for(let f:File in files){ // left hand assignment not allowed
    doSomething(f as File) // cannot convert string to File
} 

这不可能吗?

【问题讨论】:

  • 应该是for (let f of files)in 你会得到密钥,of 你会得到值。所以in 的行为类似于Object.keys (obj).forEach( key =&gt; { ... } )of 的行为类似于Object.values (obj).forEach( value =&gt; { ... } )
  • 这是一个很好的提示,但使用 for of 我得到:Type FileList is not an array type or a string type
  • FileList 的定义是什么样的?
  • 它几乎什么都没有...:developer.mozilla.org/en-US/docs/Web/API/FileList 显然你不能在 FileList 中使用 for of/for in :)

标签: typescript filelist


【解决方案1】:

您不能使用

进行迭代
for(let f in files){
   doSomething(f) 
}

FileList 不是一个数组,但它确实符合它的约定(有 长度和数字索引),所以我们可以“借用”数组方法:

您必须根据长度进行迭代。

你必须遵循这个语法

for(let i = 0;i<files.length;i++){
  doSomething(files[i])
}

指api

https://developer.mozilla.org/en-US/docs/Web/API/FileList

【讨论】:

  • 只是一个小问题,是否可以通过代码将文件添加到文件列表中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 2016-06-19
相关资源
最近更新 更多