1

I'm making a JS script which takes a 2D array and draws some pictures on the screen. The array contains the data: a unique name, the picture file name, xy coordinates, and z-index. The for loop that takes the elements of the array and draws the pictures on the screen should also give them a function such that when I click on an image the computer knows and does stuff.

The problem is, at each loop I should make the function work on a specific value of the "i" variable (see the code below). I tried some little modifications, but I only managed to see the i disappear after the loop ran, or the i is at the maximum value for every item.

Is there a way to make the functions have a constant value of i, regardless of what the loop does in the meantime with the variable?

This is my very first question on StackOverflow, I'm sorry if I did something wrong. Thanks.

I already tried to "declare" i out of the for loop, this fixed the problem of the variable being deleted after the loop but now every function works for the last value of i. Then I tried to store the value of the "i-s" in a separate array, but this only made a lot of confusion in the code without fixing the problem.

var img = [];
var g = [// some stuff............................   
        ["bcc", "BELL", xbemb + 350, ybem + 542, 30]];
for (i = 0; i < g.length; i++) {
    //omissis
    //here it creates the function which should have a different
    //i value for each element but does not
    img[g[i][0]].onmousedown = function() { topo(g[i][0]); };
    //omissis
}

I click on any element but it returns "bcc" (the name of the last element in the array)

Angelo
  • 9
  • 2
  • 1
    For what you posted, `g` has length 1 so `i` will only ever have a value of 0 inside the loop, exits when the value gets to 1. – nurdyguy Apr 04 '19 at 18:38
  • While using a closure over a per-iteration allocated variable would be a common solution, I'd suggest something simpler. Since you just need a primitive value, just put it as a property on the element, which a sufficiently obscure name to avoid collisions. `img[g[i][0]].__my_key__ = g[i][0]` Then in the handler: `topo(this.__my_key__)` – ziggy wiggy Apr 04 '19 at 18:40
  • @ziggywiggy Thank you! It works. – Angelo Apr 04 '19 at 19:01

0 Answers0