Samuel Wahlberg
Samuel Wahlberg

Reputation: 151

Using a variable to change the name of another variable in the code

I have tried to search the forum and google but do not really know what to ask for so apologies if this have been answered before.

var currentLevel = 2;

var Level = function(layout, ColRow) {
  this.layout = layout;
  this.ColRow = ColRow;};

var level1 = new Level ([   1, 2, 1, 2, 2,
                            1, 1, 3, 1, 1,
                            1, 1, 1, 1, 1,
                            1, 1, 1, 1, 1],
                           [5, 4]);

var level2 = new Level ([   1, 2, 1, 2, 2,
                            1, 1, 3, 1, 1,
                            1, 1, 1, 1, 1,
                            1, 1, 1, 1, 1],
                           [2, 2]);                         


var drawTrack = function () {
id = 0;
for (var col = 0; col < level1.ColRow[0]; col ++) {
    tile[col] = [];
    for (var row = 0; row < level1.ColRow[1]; row++) {
        id = col + row*level1.ColRow[0];
        tile[col][row] = {x:0, y:0, type:"asphalt"};
        image (tiles[level1.layout[id]], col * 256, row * 256);
    }
}
};

In the example above I would like to change level1 in the code at the bottom to something like level(currentLevel).ColRow[0]. Is that possible or is there any other best practice to do this?

*edit The array solution solved my problem, thanks! The suggested link I did find before but could not see how it could change the variable within the code? Maybe I missed something.

Upvotes: 0

Views: 58

Answers (1)

shennan
shennan

Reputation: 11656

How about creating an array of levels?

var levels = [

    new Level ([1, 2, 1, 2, 2,
    1, 1, 3, 1, 1,
    1, 1, 1, 1, 1,
    1, 1, 1, 1, 1],
    [5, 4]),

    new Level ([1, 2, 1, 2, 2,
    1, 1, 3, 1, 1,
    1, 1, 1, 1, 1,
    1, 1, 1, 1, 1],
    [2, 2])

];

Then to access:

levels[currentLevel].ColRow;

Upvotes: 2

Related Questions