Why is the FileList object not an array?

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

Why is a FileList an object and not an array? The only property it has is .length , and the only way it has is .item() , which is redundant ( fileList[0] === fileList.item(0) ).

+23
javascript
source share
5 answers

Well, there may be several reasons. For example, if it were an array, you could change it. You cannot modify an instance of FileList . Secondly, but related, it may be (probably is) an idea of ​​the browser data structure, so a minimal set of features makes implementation easier.

Update in 2018: Interestingly, there is a note on the FileList in the specification :

The FileList interface should be considered as "at risk" since the general trend on the web platform is to replace such interfaces with an Array platform object in ECMAScript [ECMA-262]. In particular, this means that syntax of the form filelist.item(0) is at risk; Most other FileList software applications FileList unlikely to be affected by a possible switch to the Array type.

(What I find strange, I thought the trend was towards iterable , not Array - such as an update to NodeList marking it as iterable for compatibility with the extension syntax, for-of and forEach .)

You can also convert it to an array via Array.from(theFileList) .

+18
source share

With es6 we can now

const files = [...filesList]

Useful, for example, if you want a map over these

+26
source share

If you want to use array methods in FileList try apply

So for example:

Array.prototype.every.call(YourFileList, file => { ... })

if you want to use each

+4
source share

I think its own data type, because object-oriented programming was more than functional programming when it was defined. But modern Javascript offers functionality for transferring an array of type Datatypes to arrays.

For example, as Tim described: const files = [...filesList]

Another way to iterate FileList with ES6 is through the Array.from () method.

const fileListAsArray = Array.from(fileList)

IMO is better read than spread operator. But on the other hand, a longer code :)

+1
source share

Here are a couple of polyfills that add the toObject() function to File and the toArray() function to FileList :

 File.prototype.toObject = function () { return Object({ lastModified: parseInt(this.lastModified), lastModifiedDate: String(this.lastModifiedDate), name: String(this.name), size: parseInt(this.size), type: String(this.type) }) } FileList.prototype.toArray = function () { return Array.from(this).map(function (file) { return file.toObject() }) } var files = document.getElementById('file-upload').files var fileObject = files[0].toObject() var filesArray = files.toArray() 
0
source share

All Articles