为什么FileList对象不是数组?


76

文档:https : //developer.mozilla.org/zh-CN/docs/Web/API/FileList

为什么是FileList对象而不是数组?它唯一的属性是.length,唯一的方法是.item(),这是多余的(fileList[0] === fileList.item(0))。


2
与DOM和HTML相关的许多API以与数据结构无关的方式定义。考虑NodeLists和HTMLCollections。例如,如果一种语言不支持该foo[bar]语法怎么办?
Felix Kling 2014年

Answers:


89

好吧,可能有几个原因。例如,如果它是一个数组,则可以对其进行修改。您无法修改FileList实例。其次,但与此相关的是,它可能是(可能是)浏览器数据结构的视图,因此最少的功能集使实现更容易提供它。

您可以通过a = Array.from(theFileList)(将其转换为数组,这是ES2015方法,但是对它进行polyfill很简单)或通过a = Array.prototype.slice.call(theFileList)

2018年更新:有趣的是,该规范对以下内容进行了说明FileList

FileList接口应被视为“危险”,因为在Web平台上总的趋势是,以取代与这样的接口Array在ECMAScript中[ECMA-262]平台对象。特别是,这意味着这种语法存在filelist.item(0)风险;FileList最终迁移到Array类型后,大多数其他程序性使用都不太可能受到影响。

我觉得那张纸条很奇怪。我认为趋势iterable并非Array 如此,例如将其NodeList标记iterable为与扩展语法兼容的更新for-of,和forEach


4
由于您无法修改它,因此没有理由拥有它.push()和其他数组方法。
弗拉基米尔·科纳

@VladimirKornea(时间流逝,但是...)好吧,我有验证文件大小的用例,因此来自Array的“过滤器”派上了用场。还有许多其他“只读”方法。
estani

11

我认为这是它自己的数据类型,因为面向对象编程在定义时比函数式编程更重要。现代Javascript提供了将类似数组的数据类型转换为数组的功能。

例如,如Tim所述: const files = [...filesList]

使用ES6迭代FileList的另一种方法是Array.from()方法。

const fileListAsArray = Array.from(fileList)

IMO比散布运算符更具可读性,但是另一方面,它的代码更长:)


6

如果要在FileList上使用数组方法,请尝试 apply

因此,例如:

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

如果您想使用每个


0

这里有一对夫妇加polyfills的toObject()功能FiletoArray()功能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()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.