arrays - Why do I only see the last loaded image using this JavaScript code? -


this question has answer here:

the following code snippet intended loop through array (which contains 4 objects); each iteration supposed produce image of card. after 4 iterations, there should 4 cards side each in row.

problem: final image shows (i.e. element of myherocards[3].image). alert box shows, in sequence, each iteration: "0","1",2".

related posts refer problems using "for loops" step though array; don't think that's problem because can given image show replacing x value of 0-3.

i suspect interaction how onload works , how loop statements evaluated, i'm stumped on details.

function startingcardlayout(){     var nextherocard=0;     var x=0;     (i=0;i<=2;i++){         myherocards[x].image.onload = function (){ctx.drawimage(myherocards[x].image,(xfirstcol+(x*xcolinc)),100,xcardsize,ycardsize);}         alert(x);         x=x+1;     } } 

you're assigning each of these array elements function defined here:

function () {       ctx.drawimage(myherocards[x].image,                    (xfirstcol+(x*xcolinc)),                    100,xcardsize,ycardsize       ); } 

this references variable x, defined outside function. means when change variable x inside loop, these functions reference new value of x rather old value. explains why see last image: images drawing @ exact same location, , last 1 (the 1 that's on top) showing up. explains why you're seeing correct values of x inside loop , why works when hardcode numbers - inside loop, fine, after loop finished functions created sharing same value of x.

to address this, can use technique, creates local copy of variable x:

myherocards[x].image.onload = function(x) {        return function () {            ctx.drawimage(myherocards[x].image,                (xfirstcol+(x*xcolinc)),                100,xcardsize,ycardsize            );        } } (x); 

here, variable x inside of function fresh copy of current value of variable x outside function.

generally speaking, if you're working loops in javascript , want create number of functions inside loop reference changes during loop (here, x, more generally, loop counter), might want use doubly-nested-function idiom:

 var thingy = function(values, i, care, about) {      return function() {          // code uses values care      }  } (values, i, care, about); 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -