1

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 .

asked Dec 15, 2014 at 6:24

1 Answer 1

2

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.

answered Dec 15, 2014 at 6:27
Sign up to request clarification or add additional context in comments.

2 Comments

thank you soo much so simple and it makes sense just been up all nite trying to gets things finished off and polished for hand in :D
@andrewhutchings nothing to worry about. Take some good sleep and happy coding.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.