Javascript" for"循环函数序列

时间:2016-05-31 09:36:37

标签: javascript for-loop

我有一些像这样的javasctipt代码https://jsfiddle.net/vhzqvx2e/20/ 如果您选择4个文件并查看控制台,您将看到此

1 
2 
3 
4 
4 
Object { name: "FireShot Capture 4", size: 54714, type: "image/png", preview: "data:image/png;base64,"[…] } 
4 -
Object { name: "FireShot Capture 4", size: 54714, type: "image/png", preview: "data:image/png;base64,"[…] }
4 - 
Object { name: "FireShot Capture 4", size: 54714, type: "image/png", preview: "data:image/png;base64,"[…] } 
4 - 
Object { name: "FireShot Capture 4", size: 54714, type: "image/png", preview: "data:image/png;base64,"[…] }

正如你在fisrt所见,我看到完整循环console.log(this.count);然后我的所有代码都在最后一个循环中运行(图片大小和最后一个图片的名称)。我怎样才能使读者和SomeCl.processM(info);在每个循环中运行,而不是在4次后运行?

1 个答案:

答案 0 :(得分:1)

  • 包装Filereader对象创建和'加载'使用它自己的词法范围在IIFE函数内回调
  (function(file) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    info.preview = e.target.result;
                    console.log(SomeCl.count + " -")
                    SomeCl.processM(info);
                };
                reader.readAsDataURL(files[i]);
      })(files[i]);

https://jsfiddle.net/bfzmm1hc/1