为什么FileList对象不是数组?
文档: https://developer.mozilla.org/en- US / docs / Web / API / FileList
为什么 FileList
一个对象而不是一个数组?它唯一的属性是 .length
,它唯一的方法是 .item()
,这是多余的( fileList [0] === fileList.item(0)
)。
Why is FileList
an object rather than an array? The only property it has is .length
and the only method it has is .item()
, which is redundant (fileList[0] === fileList.item(0)
).
嗯,可能有几个原因。首先,如果它是一个数组,你可以修改它。您无法修改 FileList
实例。其次但是相关的,它可能(可能是)浏览器数据结构的视图,因此最小的功能集使实现更容易提供它。
Well, there could be several reasons. For one, if it were an array, you could modify it. You can't modify a FileList
instance. Secondly but related, it could be (probably is) a view onto a browser data structure, so a minimal set of capabilities makes it easier for implementations to provide it.
2018年更新:有趣的是,规范有一个关于 FileList
的注释:
Update in 2018: Interestingly, though, the spec has a note on FileList
:
FileList
接口应被视为有风险,因为Web平台的一般趋势是用ECMAScript中的Array
平台对象替换此类接口[ECMA- 262]。特别是,这意味着排序filelist.item(0)
的语法存在风险;大多数其他程序使用FileList
不太可能受到最终迁移到Array
类型的影响。
The
FileList
interface should be considered "at risk" since the general trend on the Web Platform is to replace such interfaces with theArray
platform object in ECMAScript [ECMA-262]. In particular, this means syntax of the sortfilelist.item(0)
is at risk; most other programmatic use ofFileList
is unlikely to be affected by the eventual migration to anArray
type.
(我觉得很奇怪,我认为趋势是朝向可迭代
,而不是数组
—例如更新 NodeList
将其标记为 iterable
,以便与扩展语法兼容, for-of
和 forEach
。)
(Which I find odd, I thought the trend was toward iterable
, not Array
— such as the update to NodeList
marking it iterable
for compatibility with spread syntax, for-of
, and forEach
.)
您还可以将其转换为一个数组通过 Array.from(theFileList)
。
You can also convert it to an array via Array.from(theFileList)
.