【问题标题】:Can't use forEach with Filelist不能将 forEach 与 Filelist 一起使用
【发布时间】:2017-04-15 14:33:57
【问题描述】:

我正在尝试遍历Filelist

console.log('field:', field.photo.files)
field.photo.files.forEach(file => {
   // looping code
})

如您所见,field.photo.files 有一个Filelist

如何正确循环field.photo.files

【问题讨论】:

  • Array.prototype.forEach.call(field.photo.files, file => console.log(file));
  • 不是数组吗?这是 node.js 吗?
  • @connexo:不,field.photo.files 是在FileList 上原型化的对象;就像HTMLCollection,它的原型链中没有Array.prototype
  • 简单的for loop工作:)

标签: javascript file


【解决方案1】:

FileList 不是Array,但它确实符合其约定(具有length 和数字索引),因此我们可以“借用”Array 方法:

Array.prototype.forEach.call(field.photo.files, function(file) { ... });

由于您显然使用的是 ES6,您也可以使用新的 Array.from 方法将其设为正确的 Array

Array.from(field.photo.files).forEach(file => { ... });

【讨论】:

  • 奇怪,我明白了:Building.vue?92ca:292 Uncaught (in promise) TypeError: Cannot convert undefined or null to object(…)Array.from
  • 好吧,你确定你的变量是field.photo.files吗?我没有检查...
  • @Amadan field.photo.files 正是console.log 在我的问题中显示的内容。
  • 你也可以使用扩展运算符[...field.photo.files].map(file => {});
  • @mcjlnrtwcz 除了易读性,我什么都想不出来。
【解决方案2】:

您也可以使用简单的 for 进行迭代:

var files = field.photo.files;

for (var i = 0; i < files.length; i++) {
    console.log(files[i]);
}

【讨论】:

    【解决方案3】:

    在 ES6 中你可以使用:

    [...field.photo.files].forEach(file => console.log(file));
    

    参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

    【讨论】:

      【解决方案4】:

      lodash 库有一个 _forEach 方法循环遍历所有集合实体,例如数组和对象,包括 FileList:

      _.forEach(field.photo.files,(file => {
           // looping code
      })
      

      【讨论】:

        【解决方案5】:

        以下代码在 Typescript 中

        urls = new Array<string>();
        
        detectFiles(event) {
           const $image: any = document.querySelector('#file');
           Array.from($image.files).forEach((file: any) => {
              let reader = new FileReader();
              reader.onload = (e: any) => { this.urls.push(e.target.result); }
              reader.readAsDataURL(file);
           }
        }
        

        【讨论】:

          【解决方案6】:

          如果您使用的是 Typescript,您可以执行以下操作: 对于类型为 FileList[]File[] 的变量 files,请使用:

          for(let file of files){
              console.log('line50 file', file);
          }
          

          【讨论】:

            猜你喜欢
            • 2014-05-21
            • 1970-01-01
            • 1970-01-01
            • 2019-04-08
            • 1970-01-01
            • 2016-04-02
            • 2011-06-03
            相关资源
            最近更新 更多