Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the FileList object an array?

Tags:

javascript

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

like image 751
Vladimir Kornea Avatar asked Aug 15 '14 20:08

Vladimir Kornea


People also ask

Is the FileList object an array?

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.

What is a FileList object?

FileList is an object which represents an array of individually selected files from the underlying system.

How do I loop a FileList?

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.


2 Answers

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.

like image 84
T.J. Crowder Avatar answered Oct 13 '22 02:10

T.J. Crowder


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

like image 29
Valentin Rapp Avatar answered Oct 13 '22 00:10

Valentin Rapp