Skip to content Skip to sidebar Skip to footer

Game Code Breaking When Setting Variable

This game code seems fine, but it's not working: //Get canvas and context var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); //Capture keypresses v

Solution 1:

Need to set it as an object var characters = {};

Solution 2:

  1. Variable "characters" must be an object. var characters = {};
  2. charList should not be initialized with "var" keyword because it's not a new variable so it's just characters.charList = [];
  3. On row 42 it's not characters[0].type but characters.Xantar.typeJSFiddle

Solution 3:

As noted before, you need to assign an object to your characters variable before you'll be able to access properties in it.

Just declaring it with var characters; will assign it the value of undefined and trying to access undefined.charList and assign an empty array to it will fail.

A more proper, fail resistant, and readable way of declaring it would be building the empty data structure, like so:

var characters = {
    charList: []
};

Also, adding to the end of an array is more safe using array.push() than indexing by array.length, i.e.

characters.charList.push(Name);

rather than

characters.charList[characters.charList.length] = Name;

Post a Comment for "Game Code Breaking When Setting Variable"