JavaScript数组访问问题

时间:2014-12-15 06:24:55

标签: javascript arrays

嗨,大家需要一些帮助,我有一个循环如下,需要通过计算玩家根据评论玩具可以看到哪些访问者工作以及哪些不用来更新分数。

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;
        //}
    }
}

这是包含数据的对象

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: ''}
    };

我试图错误地访问它,我目前在运行socket.io的node.js服务器上运行代码

1 个答案:

答案 0 :(得分:2)

您有'tile1' ..... 'tile9',但您的第一次循环迭代会查找tile0原因var i = 0

tile0不存在。创建它,或使用:

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

此外,console.log(game.tile['tile' + i]);工作的原因是导致var i=1&gt;&gt;的下一循环迭代。调用并返回'tile1',并尝试访问null之类的["tile0"]["player"]属性。