여러 개의 다른 zip 파일을 포함하는 zip 파일을로드하는 함수를 코딩하고, 이들을 반복하고, 결과를 하나의 집계 된 csv로 병합하고 추출하는 모든 csv 파일을 추출합니다. 내가 만난 문제는 csv의 내용을 비동기로 파일 이름이나 디렉토리에 매핑 할 수 없다는 것입니다. 다음은 myzip2가 JSZIP 객체이고 파일이 파일 이름의 사전이며 csvfiles가 출력 배열 인 코드입니다.
for (var key in files) {
if ( files[key].name.includes('.csv') ) {
myzip2.file( files[key].name ).async("string").then( function(result) {
csvfiles.push( $.csv.toArrays(result) ); // contains the csv content
csvfiles.push( files[key].name ); // undefined in async
});
)
)
csv 콘텐츠와 파일 이름을 동시에 푸시하고 싶지만 파일 이름은 함수 내에서 정의되지 않았습니다. 어떻게받을 수 있습니까? 나는 내 문제를 검색 할 기회가 많지 않았고, 아마도 정확한 표현이 부족했을 것이다.
감사
누구든지 같은 문제가 발생하는 경우 파일 이름을 콘텐츠와 일치시키는 것은 화살표 함수로 해결되는 종료 문제이지만 올바른 zip 파일 이름을 일치시키는 것은 JSZip이 현재 객체에 추가되는 문제입니다. new JSZip()
이전 항목을 지워야하는 경우 사용 합니다.
전체 코드, zipfiles는 mainzip 안에 포함 된 zipfiles 이름 목록입니다.
var csvfiles = []
for (var i = 0; i < zipfiles.length; i++) {
let thiszipname = zipfiles[i];
let thiszip = mainzip.file( thiszipname ).async("blob");
var newzip = new JSZip();
newzip.loadAsync( thiszip ).then(
subzip => {
let subfiles = subzip.files;
Object.keys(subfiles).forEach( filename => {
if ( filename.includes('.csv') ) {
subzip.file( filename ).async("string").then(
readData => {
var obj = $.csv.toObjects(readData); // works great
obj['csvfile'] = filename // correct file
obj['zipfile'] = thiszipname; // incorrect zipfile...
csvfiles.push( obj );
}
);
}
})
}
)
} console.log(csvfiles)
문제는 files
변수 의 어휘 범위와 관련이 있습니다. 와 관련이 없습니다 async
.
클로저는 주변 상태 (어휘 환경)에 대한 참조와 함께 번들로 묶인 (포함 된) 함수의 조합입니다. 즉, 클로저는 내부 함수에서 외부 함수의 범위에 대한 액세스를 제공합니다. JavaScript에서는 함수가 생성 될 때마다 클로저가 생성됩니다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
루프에서이 작업을 수행 할 때 "루프에서 폐쇄"문제를 처리해야합니다.
동일한 링크 다음에있는 " 루프에서 클로저 생성 : 일반적인 실수 " 섹션을 확인 하십시오. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
익명 함수를 화살표 함수로 바꾸면 작동합니다.
for (var key in files) {
// It's important to set the value of the `files[key]` to the separate variable.
// Because otherwise the last element of the `files` will be captured in the closure for the expression `files[key]`.
const fileName = files[key].name;
myzip2
.file(fileName)
.async("string")
// Arrow function `result => {}` creates a closure that captures `fileName` variable from the external scope
.then(result => {
csvfiles.push($.csv.toArrays(result));
csvfiles.push(fileName);
});
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다