Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

javascript - Why isn't the FileList object an array?

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

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)).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

You can convert it to an array via a = Array.from(theFileList) (that's an ES2015 method, but it's trivial to polyfill it) or via a = Array.prototype.slice.call(theFileList).

Update in 2018: Interestingly, though, the spec has a note on FileList:

The FileList interface should be considered "at risk" since the general trend on the Web Platform is to replace such interfaces with the Array platform object in ECMAScript [ECMA-262]. In particular, this means syntax of the sort filelist.item(0) is at risk; most other programmatic use of FileList is unlikely to be affected by the eventual migration to an Array type.

I find that note 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...