0

I'm trying to create 4 different audio objects in JS in a programmatic way. I have seen similar threads to this like in this thread: "How do I create dynamic variable names inside a loop?"

However, the change in variable name capitalises on the looping stage. Inside the thread there are also answers using the this keyword, though I am unsure how to use that programmatically in a loop.

Attempt:

var buttonColours = ["red", "blue", "green", "yellow"]
var sounds = [];

for (var i=0; i < buttonColours.length; i++) {
  sounds[i] = new Audio(`sounds/${buttonColours[i]}.mp3`); // Eg. name of audio file - 'blue.mp3'
}

console.log(sounds);

Current Output:

 [audio, audio, audio, audio]

Desired Output (each storing a different Audio object as they play different sounds):

 [redSound, blueSound, greenSound, yellowSound]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
jchua
  • 354
  • 1
  • 4
  • 15
  • 1
    Why not simply use an object where you can name the keys? – VLAZ Oct 30 '20 at 06:53
  • the log is just saying they are `audio` objects. I'm not sure the structure of said object but if you look for it's path property I bet it's `sounds/red.mp3` etc. – pilchard Oct 30 '20 at 07:21

1 Answers1

0

Instead of storing the audio objects in an array use an object instead. And to put them in use you can loop over the keys of the object using Object.keys(sounds)

var buttonColours = ["red", "blue", "green", "yellow"]
var sounds = {};

for (var i=0; i < buttonColours.length; i++) {
  sounds[buttonColours[i]+"Sound"] = new Audio(`sounds/${buttonColours[i]}.mp3`); // Eg. name of audio file - 'blue.mp3'
}

console.log(sounds);
//{redSound: audio, blueSound: audio, greenSound: audio, yellowSound: audio}
Charles
  • 227
  • 1
  • 5