我有一个包含四个变量的列表。我想随机选择一个来使用。我的变量看起来像...
laneRect_one = new Phaser.Rectangle(0, 0, game.width, game.height / 4 - 50);
laneRect_two = new Phaser.Rectangle(0, game.height / 4 - 50, game.width, game.height / 4 - 50);
laneRect_three = new Phaser.Rectangle(0, game.height / 4 * 2 - 100, game.width, game.height / 4 - 50);
laneRect_four = new Phaser.Rectangle(0, game.height / 4 * 3 - 150, game.width, game.height / 4 - 50);
所以我的第一次尝试是将变量名称放入数组中,例如
var laneArr = ["laneRect_one", "laneRect_two", "laneRect_three", "laneRect_four"];
然后执行laneArr[Math.floor(Math.random() * LaneArr.length)]
,但很快就明白了,这永远不会起作用,因为我只是使用一个字符串,没有指针到上面我的实际变量。
我是否可以随机选择上面定义的四个变量之一?
最佳答案
您的问题是因为您将字符串放入数组中,而不是变量的值。要实现此功能,只需删除引号即可:
var laneRect_one = 'one';
var laneRect_two = 'two';
var laneRect_three = 'three';
var laneRect_four = 'four';
var laneArr = [laneRect_one, laneRect_two, laneRect_three, laneRect_four];
var random = laneArr[Math.floor(Math.random() * laneArr.length)]
console.log(random);
关于javascript - 从变量列表中随机选择变量 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43043763/