让编译器读取一个字符串作为变量

get the compiler to read a string as a variable

我正在尝试在 Phaser 3 中制作的游戏中播放随机音频片段。我希望在特定事件发生时播放以下任何内容:

audioBanshee0 = this.sound.add('audioBanshee0',{volume: 0.5});     
audioBanshee1 = this.sound.add('audioBanshee1',{volume: 0.5});     
audioBanshee2 = this.sound.add('audioBanshee2',{volume: 0.5});     
audioBanshee3 = this.sound.add('audioBanshee3',{volume: 0.5});    
audioBanshee4 = this.sound.add('audioBanshee4',{volume: 0.5}); 

我试过以下方法:

var ref = Math.floor(Math.random() * Math.floor(5));
const audioBansheeScreech = "audioBanshee" + ref;
audioBansheeScreech.play();

我收到一条错误消息

audioBansheeScreech.play() is not a function

因为audioBansheeScreech是一个字符串。我可以用 for 循环和 if 语句来解决这个问题,但我宁愿避免。

将它们移动到一个对象中可能更容易,然后您可以使用字符串调用它们:

const audioBanshees = {
  audioBanshee0: this.sound.add('audioBanshee0',{volume: 0.5}),
  audioBanshee1: this.sound.add('audioBanshee1',{volume: 0.5}),
  audioBanshee2: this.sound.add('audioBanshee2',{volume: 0.5}),
  audioBanshee3: this.sound.add('audioBanshee3',{volume: 0.5}),
  audioBanshee4: this.sound.add('audioBanshee4',{volume: 0.5})
}

let ref = Math.floor(Math.random() * Math.floor(5));

const audioBansheeScreech = audioBanshees["audioBanshee" + ref];

audioBansheeScreech.play()

虽然 IMO,但这里的数组会更合乎逻辑且更易于阅读:

const audioBanshees = [
  this.sound.add('audioBanshee0',{volume: 0.5}),
  this.sound.add('audioBanshee1',{volume: 0.5}),
  this.sound.add('audioBanshee2',{volume: 0.5}),
  this.sound.add('audioBanshee3',{volume: 0.5}),
  this.sound.add('audioBanshee4',{volume: 0.5})
]

let ref = Math.floor(Math.random() * Math.floor(5));

const audioBansheeScreech = audioBanshees[ref];

audioBansheeScreech.play()