JavaScript array access issues
Hi guys, I need help. I have a loop that needs to update the score by counting the number of tiles the player has according to the comments, the toy can see which accessors are working and which are not.
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 an object containing 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: ''}
};
I am trying to access it incorrectly, I am currently running the code on a node.js server running with socket.io
source to share
You have 'tile1'
... 'tile9'
but your first loop iteration will look for tile0
causevar i = 0
tile0
does not exist . 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 why the work console.log(game.tile['tile' + i]);
is to cause the next iteration of the loop, where var i=1
→ 'tile1'
invoked and returns, and the properties null
, such as the ["tile0"]["player"]
attempted access.
source to share