Search code examples
javascriptfor-loopobjectgame-development

This value in object for loop


I'm trying to create 2D array of brick game. how I get this value of object that at defining stage, if I use this code,it returned undefined

const bricks = [];
for (let r = 0; r < brickRow; r++) {
  bricks[r] = []
for (let c = 0; c < brickCol; c++) {
    bricks[r][c] = {
      x:r*(brickWidth+gap)+10,
      y:c*(brickHeight+gap)+10,
      bLeft:this.x,
      bTop:this.y,
      bRight:this.x+brickWidth,
      bBottom:this.y+brickHeight
    }
}  

accessing via bricks[r][c].x inside object not work

use x failed, it was global x, not the item brick I want


Solution

  • First you have some undefined variables I hope you really set them out Example: brickRow

    Second you can set the X and Y outside from the object and use that property This is not a correct way to use your porperty on the same object where you set it.

    const bricks = [];
    let brickRow,brickCol,brickWidth,brickHeight,gap;
    for (let r = 0; r < brickRow; r++) {
      bricks[r] = []
    for (let c = 0; c < brickCol; c++) {
      let xTemp=r*(brickWidth+gap)+10;
      let yTemp=c*(brickHeight+gap)+10;
        bricks[r][c] = {
          x:xTemp,
          y:yTemp,
          bLeft:xTemp,
          bTop:yTemp,
          bRight:xTemp+brickWidth,
          bBottom:yTemp+brickHeight
        }
    } 
    }