andrew hutchings
andrew hutchings

Reputation: 366

JavaScript array access issues

I have a loop as follows. That needs to update a score by counting, how many tiles a player has. As per comments, the toy can see, which accessors work and which don't:

Player.prototype.calculateScore = function(){
    for(i = 0; i < 9; i ++){

        //works and prints tile1 player contents
        console.log(game.tile.tile1.player);

        //doesnt work 
        console.log(game.tile['tile' + i]['player']);

        //works and prints the entire tile1 object
        console.log(game.tile['tile' + i]);

        //if(game.tile['tile' + i]['player'] == this.name){
        //  this.score = this.score + 1;
        //}
    }
}

here is the object containing the data

function Game(){
    this.tile = {
        'tile1' : {card: '', player: ''},
        'tile2' : {card: '', player: ''},
        'tile3' : {card: '', player: ''},
        'tile4' : {card: '', player: ''},
        'tile5' : {card: '', player: ''},
        'tile6' : {card: '', player: ''},
        'tile7' : {card: '', player: ''},
        'tile8' : {card: '', player: ''},
        'tile9' : {card: '', player: ''}
    };

Am I trying to access it incorrectly? I am currently running code on a node.js server running with socket.io .

Upvotes: 1

Views: 64

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

You have 'tile1' ..... 'tile9' but your first loop iteration will look for tile0 cause var i = 0

tile0 does not exists. Create it, or use:

for(var i = 1; i < 10; i++) {
    console.log(game.tile['tile' + i].player); // will work cause "tile1" exits
}

Furthermore, the reason that console.log(game.tile['tile' + i]); works, is cause in the next loop iteration where var i=1 >> 'tile1' gets called and returned, and no null properties like ["tile0"]["player"] were tried to get accessed.

Upvotes: 2

Related Questions