Discord
Login
Community
DARK THEME

JavaScript: cannot read properties of undefined (reading "remove")

When checking a variable in an object inside an array, an error is returned. What could be the problem? I tried to return the value from the update() function, but it didn't help either

  for(let i = bullist.length;i>=0;i--){
    if(bullist[i].remove  === true){
      bullist.splice(i,1);
    }
  }

Class

bullet = class{
  constructor(x,y){
  this.x=x;
  this.y=y;
  this.w=3;
  this.h=3;
  this.speed=1;
  this.dir=(Math.atan2(mouse.y - this.y, mouse.x - this.x));
  this.remove=false;
  this.colorArr=["#0000AA","#5555FF","#00AA00","#55FF55","#00AAAA","#55FFFF","#AA0000","#FF5555","#AA00AA","#FF55FF","#AA5500","#FFFF55"];
  this.color = this.colorArr[Math.floor(Math.random() * 12)];
  }
  
  update(){
    this.x = this.x+this.speed*Math.cos(this.dir);
    this.y = this.y+this.speed*Math.sin(this.dir);
    
    if(Math.abs(this.x-eminem.x)<(this.w+eminem.w)/2 &&
       Math.abs(this.y-eminem.y)<(this.h+eminem.h)/2){
      this.remove=true;
    }
  }
  
  draw(){
    screen.fillRound(this.x,this.y,this.w,this.h,this.color);
  }
}

I guess it should be

  for(let i = bullist.length-1;i>=0;i--){    // << bullist.length-1 
    if(bullist[i].remove  === true){
      bullist.splice(i,1);
    }
  }

👀 What? How? Thanks a lot for the reply!!! So far I'm just learning JavaScript, could you tell me why it doesn't work correctly without "-1"?

The numbering starts from the element with index "0".

If there is only one element in the list ( list.length returns one ), you can only read the element with index list[0] .

Thanks a lot for the reply

That is, he was trying to address something that does not exist!!!

The fact that the index of the array starts from 0, and the actual length is one more - I know this, but this time I did not pay attention to it 🤦‍♂️

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community