不能与文件列表一起使用forEach

我正在尝试通过Filelist循环:

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

正如你所看到的,field.photo.files有一个Filelist:

enter image description here

如何正确地循环通过field.photo.files?

105707 次浏览

FileList不是Array,但它符合它的契约(有length和数值索引),所以我们可以“借用”Array方法:

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

因为你显然是在使用ES6,你也可以使用新的Array.from方法使它成为一个合适的Array:

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

如果你正在使用Typescript,你可以这样做: 对于类型为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);
}
}