变量名最后有一个变量

时间:2013-12-25 10:31:45

标签: javascript variables

if (playerturn == 1) {
     currentpos1 = startpos1 + dicetotal;
     prevpos1 = currentpos1 - dicetotal;
 } else {
     currentpos2 = startpos2 + dicetotal;
     prevpos2 = currentpos2 - dicetotal;
 }

我知道这与其他问题略有重复,但我仍然不理解答案。这是一个垄断棋盘游戏,最多可以有6个玩家。我想清理代码,因为唯一改变的是变量的最后一部分。

Currentpos(i),Prevpos(i),Startpos(i)是变量名。那么我如何将变量连接成变量名呢?

1 个答案:

答案 0 :(得分:2)

您可以使用对象而不是变量。

var players = {
      playername : { 
          currpos:'val',
          prevpos:'val',
          startpos:'val',
          ....
      },
      ....

  }

添加新播放器

players['playername1'] = { 
          currpos:'val',
          prevpos:'val',
          startpos:'val',
          ....
      }

使用率是players['playername'].currpos所以在你的情况下jus players['playername'+playerturn].currpos = players['playername'+playerturn].startpos + dicetotal;

或数组

var players = [
    { 
        currpos:'val',
        prevpos:'val',
        startpos:'val',
        ....
    },
    { 
        currpos:'val',
        prevpos:'val',
        startpos:'val',
        ....
    }
];

添加新玩家:

 players.push({ 
        currpos:'val',
        prevpos:'val',
        startpos:'val',
        ....
    });

使用情况为players[0].currpos,因此在您的情况下players[playerturn].currpos = players[playerturn].startpos + dicetotal