0

I have a strange behavior with a simple function in javascript. I write in a matrix, but when I read it again, I can't see the changes. Can someone please explain me why? Here is the code:

this.map = [
    '## ### ##',
    '#   #   #',
    '# # . # #',
    '#  ## # #',
    '##  #   #',
    '#*# ## ##',
    '    ##   ',
    '#########'
];
this.check_collision = function ( x, y ) { 
    var l = Math.floor ( y / this.tile_size );
    var c = Math.floor ( x / this.tile_size );

    if ( this.map[ l ] != undefined ) { 
        if ( this.map[ l ][ c ] != undefined ) { 
            if ( this.map[ l ][ c ] == '#' ) { 
                return true;
            }   
            else if ( this.map[ l ][ c ] == '.' || this.map[ l ][ c ] == '*' ) { 
                this.map[ l ][ c ] = ' ';
                console.debug ( "'" + this.map[ l ][ c ] + "'" );
            }   
        }   
    }   
    return false;
};  

The console.debug() prints '.' or '*', but I write the char ' ' the line above

outis
  • 75,655
  • 22
  • 151
  • 221
Andrea Carron
  • 1,001
  • 13
  • 22
  • Test `alert` instead of `console.debug`. Do you still get the same result? – Rob W Oct 27 '11 at 08:29
  • 2
    The [sample code](http://sscce.org/) is incomplete. What's actually stored in `this.map[l]`? If it's a string, strings are immutable. – outis Oct 27 '11 at 08:36
  • The code looks ok to me. Usually when these things happen I double check that the code running in the browser is the actual code I expect. Use a debugger in your browser to see the lines of code actually running, that should show you what's going on. – Kraylog Oct 27 '11 at 08:41
  • It was a string. I used the replaceAt() method from [here](http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) and now it works. Thank s @outis – Andrea Carron Oct 27 '11 at 09:07
  • The sample code still needs a sample value for `this.map`. – outis Oct 27 '11 at 21:00

1 Answers1

1

The reason the assignment is ignored is that strings are immutable. You can't change any portion of a string.

Depending on the rest of your design, it might make more sense to convert this.map into an array of arrays.

outis
  • 75,655
  • 22
  • 151
  • 221