“合并” 2个变量来声明一个新变量?

时间:2019-05-29 19:10:23

标签: javascript variables

我是编码的新手,我正在尝试声明一个变量,该变量引用2个先前声明的“组合”变量,如下所示:

var player1 = "Red", player2 = "Blue", player3 = "Green";
var p=1;
var Red = {x: 2, y: 4};
var Blue = {x: 6, y: 2};
var Green = {x: 8, y: 1};

var x = player+p.x; // should be player+1 so "Red" so x=2 
var y = player+p.y; // should be y=4

console.log(x);
console.log(y);

x和y应该是玩家n°p的坐标,具体取决于该玩家的颜色(在本例中为n°1)。

我希望它足够清楚!谢谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用数组来满足我的需求:

var players = ["Red", "Blue", "Green"];
var p = 1;
console.log(players[p]);

如果您需要每个玩家的更多信息,则可以是一系列对象:

var players = [{color: 'Red', x: 2, y: 3}, // etc]

答案 1 :(得分:1)

您可能正在搜索array中的objects

var players = [
  {
    name: "Red",
    x: 2,
    y: 4
  },
  {
    name: "Blue",
    x: 6,
    y: 2
  },
  {
    name: "Green",
    x: 8,
    y: 1
  }
];

players.forEach((player,index)=>{
  console.log(`Player ${index+1} = ${player.name} position is = x:${player.x},y:${player.y}`);
});

这样,您可以执行以下操作来访问所需的元素:players[index]。要获得其属性,您只需要这样命名:players[index].name作为名称。