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
Looking at your first code I would have guessed that it works.
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 https://jsfiddle.net/ and share the link?
Thanks and have a nice day,
Michael
The JSFiddle is empty.
By the way, what library are you using? Is that jQuery?
yes
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
?
只有ev没有i,第92行输出了for循环的i值,第96行输出了ev值,第97行并没有输出for循环的i值,而是数字1,我猜测这个值是文件数量,但我并不知道这个第97行i代表什么,我尝试输出(ev.i)时控制台输出undefined。
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.
Hello,
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
good
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小提琴 - 代码游乐场 (jsfiddle.net)
Thank you friend
Thank you mikomk,thank、thank