JSHint 警告:在引用外部作用域变量的循环中声明的函数可能会导致语义混乱。 (文件,reader)

JSHint warning: Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (document, reader)

我刚刚在我的项目上设置了 JSHint,它警告我:

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (document, reader)

我如何重新安排下面的代码来解决这个问题并让 JSHint 满意?

我正在写 ES6 规范。

const imageUploadPreview = document.getElementById('image-upload-preview');


for (const file of files) {

let reader = new FileReader();

reader.readAsDataURL(files[i]);
reader.onloadend = () => {
    let previewDiv = document.createElement('div');
    previewDiv.style.backgroundImage = 'url(' + reader.result + ')';
    imageUploadPreview.append(previewDiv);
};

}

更新

根据鲁本下面的回答,我得出以下结论:

const imageUploadPreview = document.getElementById('image-upload-preview');

function processFile(file) {

    if (file === undefined) {
        return;
    }

    let reader = new FileReader();

    reader.onloadend = () => {
        let previewDiv = document.createElement('div');
        previewDiv.style.backgroundImage = 'url(' + reader.result + ')';
        imageUploadPreview.append(previewDiv);
    };
    reader.readAsDataURL(file);

}

for (const file of files) {
    processFile(file);
}

这通过了所有 JSHints 测试并按照我之前的代码工作。

托尼.

您可以通过递归重新使用 Filereader 来避免循环,就像他们所做的那样 :

const imageUploadPreview = document.getElementById('image-upload-preview');

processFile(fileList) {
  const file = fileList.pop();
  if (file === undefined) {
    return;
  }

  reader.onloadend = () => {
    let previewDiv = document.createElement('div');
    previewDiv.style.backgroundImage = 'url(' + reader.result + ')';
    imageUploadPreview.append(previewDiv);
    
    // Call the next function in the recursion
    processFile(fileList);
  };
  reader.readAsDataURL(files[i]);
}

processFile(files);