javascript - Unable to access my array -


i keep getting error cannot set property '0' of undefined @ create2darray.

mind explaining what's wrong logic here? know it's rookie mistake cause still haven't gotten hang of arrays.

const row = 10; const col = 11; const size = 64;  var canvas = document.getelementbyid("canvas"); var surface = canvas.getcontext("2d"); const image = new image(); image.src = "box_image.png";  //creating tile function box() {     this.xaxis = 0;     this.yaxis = 0;     this.img = image; }  create2darray();  //creating map var map = [];  function create2darray() {     (var i=0; < row; i++){         map[i] = [];         (var j=0; j<col; j++){             map[i][j] = new box();         }     } } 

you should aware of variable hoisting here.

the way declared map, declared , initialized after create2darray call.

there 2 catches here

  1. variables declared , defined anywhere in function, hoisted top of function, declarations not initialization. in case, var map; gets hoisted not var map = []

  2. functions hoisted no matter delcared , hence though method declaration @ end, still able call. when have function expression, run same issue createarray not defined, if have this.

    var create2darray = function() {    (var = 0; < row; i++) {         map[i] = [];         (var j = 0; j < col; j++) {           map[i][j] = new box();         }   } } 

const row = 10;  const col = 11;  const size = 64;    var canvas = document.getelementbyid("canvas");  var surface = canvas.getcontext("2d");  const image = new image();  image.src = "box_image.png";    //creating tile  function box() {    this.xaxis = 0;    this.yaxis = 0;    this.img = image;  }    var map = [];    create2darray();    //creating map      function create2darray() {    (var = 0; < row; i++) {      console.log("creating box", i);      map[i] = [];      (var j = 0; j < col; j++) {                map[i][j] = new box();      }    }  }
<canvas id="canvas"></canvas>

more variable , function hoisting


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -