programing

파일 리스트가 있는 각각에 대해 사용할 수 없음

javaba 2022. 9. 16. 22:00
반응형

파일 리스트가 있는 각각에 대해 사용할 수 없음

난 루프를 통과하려고 노력중이야Filelist:

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

당신이 볼 수 있듯이.field.photo.files가 있다Filelist:

여기에 이미지 설명 입력

적절한 루프 스루 방법field.photo.files?

A FileList가 아니다Array단, 계약에는 준거하고 있습니다.length및 숫자 인덱스)를 사용하여 "수정"할 수 있습니다.Array메서드:

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

ES6를 사용하고 있는 것이 분명하기 때문에 적절한 방법으로 사용할 수도 있습니다.Array, 새로운 것을 사용하다Array.from방법:

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

다음 용도의 심플을 사용하여 반복할 수도 있습니다.

var files = field.photo.files;

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

ES6에서는 다음을 사용할 수 있습니다.

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

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

Lodash 라이브러리에는 FileList를 포함한 어레이나 오브젝트 등의 모든 수집 엔티티를 루프하는 _forEach 메서드가 있습니다.

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

다음 코드는 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);
   }
}

Typescript를 사용하는 경우 다음과 같은 작업을 수행할 수 있습니다.변수의 경우files활자로FileList[]또는File[]용도:

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

언급URL : https://stackoverflow.com/questions/40902437/cant-use-foreach-with-filelist

반응형