skip to Main Content

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

2

Answers


  1. 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
        }
    } 
    }
    Login or Signup to reply.
  2. this is undefined because this refers to this object when you call the method. You can explore more about it at this

    and to solve your problem, just:

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

    hope it will help you.Let me know your result

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search