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)
).
A FileList is an array-like object that represents a collection of File objects returned by the files property of the HTML <input> element. You can use this to access the list of files selected with the <input type="file"> element.
FileList is an object which represents an array of individually selected files from the underlying system.
One way to let us loop through each item in a file list object is to convert it to an array with the Array. from method. Then we can use the forEach method on it to loop through the file list entries. The file input has the multiple attribute so that we can select multiple files.
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 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.
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
.
I think it's its own Datatype because Object Oriented Programming was more of a thing than functional programming back when it was defined. Modern Javascript offers functionality to cast Array-like Datatypes to Arrays.
For example, like Tim described: const files = [...filesList]
Another way of iterating a FileList with ES6 is the Array.from() method.
const fileListAsArray = Array.from(fileList)
IMO it's more readable than the spread operator, but on the other hand it's longer code :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With