TypeError: undefined is not an object

Stuck again. Does anyone know how to fix this error?

Thank you.

var bunkers = [];

   function setup(){
      createCanvas(window.innerWidth, window.innerHeight);
       for (var i = 0; i < 4; i++) {
           bunkers[i] = new Bunker(i*294 + 247, height-150);
     }     
   } 

  function draw(){
      background(0);
      for (var i = 0; i < 5; i++) {
         bunkers[i].show();    
  }   
} 
 function Bunker(x, y){
      this.show = function(){
          push();
          translate(x-257, y-68);
          noStroke();
          fill(0, 100, 0);
          beginShape();
          vertex(200, 50);
          vertex(208, 50);
          vertex(208, 42);
          vertex(216, 42);
          vertex(216, 34);
          vertex(224, 34);
          vertex(224, 26);
          vertex(290, 26);
          vertex(290, 34);
          vertex(298, 34);
          vertex(298, 42);
          vertex(306, 42);
          vertex(306, 50);
          vertex(314, 50);
          vertex(314, 110);
          vertex(290, 110);
          vertex(290, 102);
          vertex(282, 102); 
          vertex(282, 94);
          vertex(274, 94);
          vertex(274, 86);
          vertex(240, 86);
          vertex(240, 94);
          vertex(232, 94);
          vertex(232, 102);
          vertex(224, 102);
          vertex(224, 110);
          vertex(200, 110);
          endShape(CLOSE);
          pop();
  }
}
Tagged:

Answers

  • Answer ✓

    @ line #12, you're accessing more Bunker objects than what has been created & stored in your array bunkers[]! #-o
    Safest way to iterate over an array is via for ( of ) btW: for (const b of bunkers) b.show();

    You should consider indenting your code better so you & others can study it easier.
    Go to https://JSFiddle.net/, copy & paste your JS code at window "JAVASCRIPT", then click at top 3rd "Tidy" button and voilà. :P

    Also consider using much tidier class syntax for your Bunker too: *-:)
    https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class

  • That worked. Thanks for all your help. I'll use Fiddle next time. I'll check out Mozilla too.

Sign In or Register to comment.