array cant be populated
function draw(data)
{
var i = 0;
var checkduplicates = new Array();
drawOne(i);
//console.log(checkduplicates) Problem!!!;
function drawOne(i)
{
//photos is a object that has been omitted for simplicity
var picinfo = photos[Math.floor(Math.random()*photos.length)];
checkduplicates.push(picinfo);
img.onload = function()
{
var ctx = document.getElementsByCla开发者_Python百科ssName("canvas")[i].getContext('2d');
// Draw pieces
ctx.drawImage(img,0,0,132,150);
//ctx.fillText("haha",0,0);
ctx.drawImage(frame,0,0,133,152);
i++;
if (i != canvaslength)
{
drawOne(i);
}
}
//console.log(checkduplicates.length);
}
}
Hey, I declared the drawOne function inside the draw function, so that the local variable checkduplicates is accessible to the inner function drawOne. However, after the drawOne function runs 16 times, the array checkduplicates is supposed to be populated with objects, which is proved by the console.log inside drawOne that shows 16 objects are in the array. However, the console.log function, which I marked with "Problem", shows that the array has only very first object meanwhile others console.logs show the array is full of objects. I dont understand why since the only way to modify the array is through the "push" method, which has been called for 16 times and if I comment out the img.onload part, the console.log with comment "problem" shows the array is full of objects. I intentionally omitted other codes for simplicity and my firebug doesnt complain for bugs. Thank you
As you are using asynchronous recursion, the initial call to drawOne
will return after the first iteration. The iterations will continue when the first image has loaded, and when you have exited out of the draw
function so that the browser regains control so that it can handle events.
So, that the array only contains a single item after the first iteration is not a problem at all, it's the expected result from the iteration method that you have used.
精彩评论