Can't use forEach with Filelist

前端 未结 6 605
栀梦
栀梦 2020-12-23 08:56

I\'m trying to loop through a Filelist:

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


        
6条回答
  •  天命终不由人
    2020-12-23 09:11

    A FileList is not an Array, but it does conform to its contract (has length and numeric indices), so we can "borrow" Array methods:

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

    Since you're obviously using ES6, you could also make it a proper Array, using the new Array.from method:

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

提交回复
热议问题