为什么 FileList 对象不是数组?

新手上路,请多包涵

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

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

原文由 Vladimir Kornea 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

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

您可以通过 a = Array.from(theFileList) (这是一个 ES2015 方法,但填充它很简单)或通过 a = Array.prototype.slice.call(theFileList) 将其转换为数组。

2018 年更新: 不过,有趣的是, 该规范FileList 上有一条注释:

FileList 接口应该被认为是“有风险的”,因为 Web 平台上的一般趋势是用 ECMAScript [ECMA-262] 中的 Array 平台对象替换此类接口。特别是,这意味着 filelist.item(0) 这种语法存在风险; FileList 的大多数其他编程用途不太可能受到最终迁移到 Array 类型的影响。

我觉得那张纸条很奇怪。 I thought the trend was toward iterable , not Array — such as the update to NodeList marking it iterable for compatibility with spread syntax, for-offorEach

原文由 T.J. Crowder 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

例如,像 Tim 描述的那样: const files = [...filesList]

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

const fileListAsArray = Array.from(fileList)

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

原文由 Valentin Rapp 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏