Javascript-使用其他变量的输入来构建变量名

时间:2019-01-30 11:07:06

标签: javascript string

是否可以使用其他变量的输入创建变量名,如下所述?查看其他类似的线程,似乎不建议使用[eval]。

我确实知道,在一定数量的变量下,将内容分组到一个数组中可能更有意义,但是目前,我想开始理解是否可以通过从其他变量构建变量名来解决

下面是我的代码,并尝试使用“模板文字”:

// Players:
  let p1 = "player1";
  let p2 = "player2";
  let activePlayers = p2;

  console.log("Active player: ", activePlayers);

if (activePlayer == "p1") {
  let score_(${p1})_upper_row1;
  let score_(${p1})_upper_row2;
  let score_(${p1})_upper_row3;
} else if (activePlayer == "p2") {
  let score_(${p2})_upper_row1;
  let score_(${p2})_upper_row2;
  let score_(${p2})_upper_row3;
}

预期的生产变量名称:

如果玩家设置为[player1]:

score_player1_upper_row1;
score_player1_upper_row2;
score_player1_upper_row3;

如果玩家设置为[player2]:

score_player2_upper_row1;
score_player2_upper_row2;
score_player2_upper_row3;

0 个答案:

没有答案