3

The following code should replace the tilemap index with a blank space, however nothing happens.

Tilemap:

var tilemap = [

     "wwwwwwwwwwwwwwww",
     "wmmmmmmmmmmmmmmw",
     "wmwmwmwwwwmwmwmw",
     "wmmbwmmmmmmwbmmw",
     "wmwwwwwwwwwwwwmw",
     "wmwmmmmssmmmmwmw",
     " mwmwwwsswwwmwm ",
     "wmwmwwwwwwwwmwmw",
     " mwmwmmmmmmwmwm ",
     "wmwmwmwwwwmwmwmw",
     "wmwmmmmmmmmmmwmw",
     "wmwmwwwwwwwwmwmw",
     "wmwmwbmmmmbwmwmw",
     "wmwmwmwwwwmwmwmw",
     "wmmmmmmmmmmmmmmw",
     "wwwwwwwwwwwwwwww",];

Code to change tilmap:

if (Player.x > j*25 && 
Player.x < j*25+25 && 
Player.y > i*25 && 
Player.y < i*25+25
) {
   tilemap[i][j] = ' ';
}

What is weird is that if it is tilemap[i] or even tilemap[j] instead of tilemap[i][j], it does what you would think it would, and tilemap[i][j] works for traversing the tilemap in the loop that it is in. In other words this changes the entire row in the tile map:

if (Player.x > j*25 &&
    Player.x < j*25+25 &&
    Player.y > i*25 &&
    Player.y < i*25+25
) {
   tilemap[i] = ' ';
}
Fanghole
  • 33
  • 4
  • This is late to be of much use, but a clean approach would be to use `var map = ["www...", ...].forEach(function(e){e.split("");});`. Then your syntax just works as expected and without dirtying the code. – Nolo Jun 28 '16 at 05:09

1 Answers1

1

tilemap is a single dimension array of strings of 16 characters each. Syntactically strings accept array notation to look up a character in them making stringgVar[i] equivalent to stringVar.charAt(i) This explains why when reading the array, tilemap[i][j] returns the j'th character in the i'th string held in tilemap without throwing an error.

And now you ran into something I have never seen before.

If you assign something to tilemap[i][j] javascript takes the i'th string from the tilemap array, treats it as a String object to which properties can be added, and adds a property named with the value of j and property value as specified on the RHS of the assignment.

If you try and read it back after assignment however, the array syntax used for reading takes precedence and you just get the j'th character of the i'th string.

Thank you for the question. Awesome!


Free Update: You can't update characters within a primitive String object, you can only use its value or parts of its value to compose a new string. Have a look into using String methods substr or substring to achieve what you want to do. (You will need to replace a complete string entry in tilemap when you update it.)
traktor
  • 17,588
  • 4
  • 32
  • 53