Can't use forEach with Filelist

前端 未结 6 495
栀梦
栀梦 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:06

    You can also iterate with a simple for:

    var files = field.photo.files;
    
    for (var i = 0; i < files.length; i++) {
        console.log(files[i]);
    }
    
    0 讨论(0)
  • 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 => { ... });
    
    0 讨论(0)
  • 2020-12-23 09:11

    In ES6 you can use:

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

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

    0 讨论(0)
  • 2020-12-23 09:12

    Following code is in 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);
          }
        }
    
    0 讨论(0)
  • 2020-12-23 09:15

    The lodash library has a _forEach method that loops through all collection entities, such as arrays and objects, including the FileList:

    _.forEach(field.photo.files,(file => {
         // looping code
    })
    
    0 讨论(0)
  • 2020-12-23 09:23

    If you are using Typescript you can do something like this: For a variable 'files' with a type FileList[] or File[] use:

    for(let file of files){
        console.log('line50 file', file);
      }
    
    0 讨论(0)
提交回复
热议问题