JavaScript array access issues Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JavaScript array access issues without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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 .

Answer

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.

We are here to answer your question about JavaScript array access issues - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji