简体   繁体   中英

JavaScript returning var in for loop

I am trying to understand code which implements canvas/context objects. This code returns an object if the sprite of that object is encountered on the canvas at a specified set of coordinates provided by a mouse button down event (as far as I can tell). Does the following code create an array of objects?

var selObj = getObjectByPixel(mx,my);

and

function getObjectByPixel(x,y) {
  gctx.clearRect(0,0,MaxX,MaxY);
  //alert(levelData.world['ExtraBlockTNT_1'].name);
  for (var objname in levelData.world) {
    var obj = levelData.world[objname];
    var sprd = spriteData[obj.definition];
    if(!sprd) continue;
    var tr = transform(obj.x, obj.y, sprd.data.width, sprd.data.height);

    gctx.save();
    gctx.translate(tr.x,tr.y);      
    gctx.rotate(obj.angle);

    gctx.fillRect(-tr.w/2, -tr.h/2, tr.w, tr.h);
    gctx.restore();
    //console.info(x,y);
    var imageData = gctx.getImageData(x, y, 1, 1);
    if (imageData.data[3] > 0) {
      return obj;
    }
  }
  return null;
}

It would seem to me that the first object in the loop will return if pixel data is encountered. If that is the case, does the loop end (which is what I assume will happen) or does it keep returning objects and store them in selObj

I'm quite confused by this code but the app runs without error so I must not be fully understanding it.

Thanks.

It does not return an array. It returns an object, see: return obj; . You can only return from a function once.

ps if the author of this code was to return an array he would have probably called it: getObjectsByPixel (note the s ).

return always ends the execution and returns to the stack at the point the function was entered.

So that means it is only returning a single object. In order to return an array, the function would have to first create the array, and then return it after the loop has finished.

I finally worked out the dynamic of the block. The loop does only return a single obj (which is what I knew anyway). The logic is, for every object sprite on the canvas, an invisible filled rectangle is created in a overlayed canvas until the mouse click coordinates are within the bounds of one of the rectangles. Then the object that that rectangle was generated from is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM