+ 2

How can I *loop* the following code? ..[]

In this code I have multiple images[] and the images have their own names[] that will be displayed when the image is clicked. For example you can click on the sunset image and the profile image changes to the sunset image. And the name of the profile image displays under the profile. Same thing for the other images. The code is already functional to where you can click on an image and the name and profile image changes, but I need to loop the code that's at the bottom of the JS. I need help looping the part that has the onClick events. In the end, the code should function just like it is now, but the Js code will be shorter. I want to loop it because I don't want to keep doing what I'm doing right now for another 100 images. Thank You. https://code.sololearn.com/WugC4ZSZCudF/#js

27th Feb 2020, 11:26 PM
Ginfio
Ginfio - avatar
2 Respostas
+ 4
Probably your loop is similar to this: https://code.sololearn.com/W2tX43I1eR2F/?ref=app You get undefined because your functions (callbacks to eventListener) don't get called inside your loop, but when the image is clicked. Add alert(i) in your function body and see what happens: You get 4 because varibles declared with "var" keyword don't belong to the loop, but to the enclosing scope. When your function is called it tries to find "i" but i=4 after loop execution. options[4] is undefined. There are some ways to solve this issue: -ES6 block-scoped "let" declarations: for(let i=0;i<4;i++){......} -Closures: https://code.sololearn.com/WX82cTkvc4lJ/?ref=app And another one but it's ugly...
28th Feb 2020, 2:53 AM
Kevin ★
+ 2
Kevin Star Thank You. It works ✔️ I never really understood the difference between var, let, and const. Now, I see the difference in the codes you gave me, I’ll read a little more carefully next time. Thank You for the info + Codes. ✔️👍
28th Feb 2020, 3:37 AM
Ginfio
Ginfio - avatar