Function calls web API and variables

The i value in the for loop cannot be called in function. ev is progressevent < FileReader >, if function (ev, i), ev is any
How to transfer the value of i to the function without changing the progressevent < FileReader > of ev

Hi @kisme and welcome to the community :wave:

Looking at your first code I would have guessed that it works. :thinking:
The second version definitively doesn’t work because i is not a parameter of the event function.

Could you put your code into an online editor like and share the link?

Thanks and have a nice day,

1 Like

The JSFiddle is empty. :slightly_frowning_face:

By the way, what library are you using? Is that jQuery?

1 Like


If closure is adopted, what should be filled in the first item。

The parentheses after the curly brace are used to immediately invoke a function (IIFE). Since a for loop just runs automatically what effect this could have.

What is the output of console.log(i) without having it as a parameter after ev?

1 Like

Only ev without i, line 92 outputs the i value of the for loop, line 96 outputs the ev value, line 97 does not output the i value of the for loop, but the number 1, I guess this value is the number of files, but I don’t know what this line 97 i represents, the console outputs undefined when I try to output (ev.i).

Can you try putting the reader.AsDataURL() line after the reader.onload block? It could have something to do with FileReader operations being asynchronous. I think the “i” in the console output is indeed the loop index, but the loop is already one step further.
Unfortunately, I don’t have the time at the moment to recreate the code myself and experiment with it.

1 Like

Both the same。


It might be a scope issue. Declaring a variable with the “var” keyword makes it available in the function scope. As Miko said there is some asynchronous stuff going on here, so when the callback function associated with the onload event is executed a while after, it will takes the value of i available in the function scope. Anyway try using the “let” keyword to declare the “i” variable in your “for” statements might solve your issue.

I think the problem going on here can be simplified to the example below:

for (let i =0; i<3;i++) {
setTimeout(() => console.log(i) ,1000)
} // 1,2,3
for (var i =0; i<3;i++) {
setTimeout(() => console.log(i) ,1000)
} // 3,3,3

Let Keyword


good :+1: :+1: :+1:
I just re-thought it here, I can realize one text and one picture, I tried using “let” as you suggested to me, and it can be achieved just like my solution. but fewer “let” statements
编辑小提琴 - JS小提琴 - 代码游乐场 (
Thank you friend

1 Like

I’m glad you could solve it @kisme.

Nice catch, @Albin.

Thank you mikomk,thank、thank

1 Like