变量在 for 循环内的函数内给了我错误的值

Variable gives me wrong value inside function inside for loop

我正在尝试构建一个小型电子应用程序。它从用户那里获取 file/files,然后将它们复制到特定文件夹,并将有关该文件的所有信息添加到数据库中。

const fs = require('fs-extra')
//sample 2 file entry
files = {"0":{"name":"File1.png","path":"A:\User Folders\Desktop\File1.png"},"1":{"name":"File2.jpg","path":"A:\User Folders\Desktop\File2.jpg"},"length":2}
window.$ = window.jQuery = require('jquery');

jQuery.each(files, function(file) {
    //this is just one of many variables I need
    currentfile = files[file].path
    fs.copy(currentfile, "./files/"+"."+files[file].name, function (err) {
        if (err) {
            console.log(err)
        } else {
            console.log(currentfile);
            //I expect this to log file1 then file2 so I can submit it to my database,
            //but it always logs file2

        }
    })
});

它一次只处理一个文件,但当我尝试处理多个文件时,它就无法正常工作(复制一个文件,更新 DOM,复制下一个文件,更新 DOM,等等)。

我想你不小心声明了一个全局范围的变量,而你可能想要局部范围。

改变这个:

currentfile = files[file].path

对此:

var currentfile = files[file].path

这将形成一个 closure,其中处理错误的匿名函数将能够访问处理 jquery [=13= 的匿名函数中的 currentfile 变量].