我正在尝试通过Filelist循环:
Filelist
console.log('field:', field.photo.files) field.photo.files.forEach(file => { // looping code })
正如你所看到的,field.photo.files有一个Filelist:
field.photo.files
如何正确地循环通过field.photo.files?
FileList不是Array,但它符合它的契约(有length和数值索引),所以我们可以“借用”Array方法:
FileList
Array
length
Array.prototype.forEach.call(field.photo.files, function(file) { ... });
因为你显然是在使用ES6,你也可以使用新的Array.from方法使它成为一个合适的Array:
Array.from
Array.from(field.photo.files).forEach(file => { ... });
你也可以用简单的for迭代:
var files = field.photo.files; for (var i = 0; i < files.length; i++) { console.log(files[i]); }
lodash库有一个_forEach方法,它循环遍历所有集合实体,比如数组和对象,包括FileList:
_.forEach(field.photo.files,(file => { // looping code })
在ES6中,你可以使用:
[...field.photo.files].forEach(file => console.log(file));
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
FileList[]
File[]
files
for(let file of files){ console.log('line50 file', file); }
下面的代码是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); } }