0

I am having trouble understanding how my foreach loop is operating.

My goal is to iterate through 1 array of strings and add the current iterations string to the src attribute of an audio object in another array, such that each audio object has a matching, unique string. They are all mp3 files that represent different sounds.

Here is what I have

const srcArr = ['sounds/crash.mp3', 'sounds/kick-bass.mp3', 'sounds/snare.mp3', 'sounds/tom-1.mp3', 'sounds/tom-2.mp3', 
'sounds/tom-3.mp3', 'sounds/tom-4.mp3'];
const audios = new Array(srcArr.length).fill(new Audio());

audios.forEach((audio, index) => {
    audio.src = srcArr[index];
});

When I run this, however, it seems that on each iteration, it is adding the audio path string to every single audio element in the audios array instead of the current audio object in the current forEach loop iteratio.

I feel as if I'm fundamentally misunderstanding something with the forEach loop.

My understanding of how I'm declaring it is that I am for looping over each audio object in the audios array, using an anonymous callback funcion that is being passed the audio object and index of that object as parameters. From there, it should simply be an assignment to the .src attribute of the object.

Could someone explain where I may be going wrong?

Thank you for the help in advance.

Caleb Renfroe
  • 183
  • 1
  • 13
  • It's a side-effect of `fill`. ["Value to fill the array with. Note all elements in the array will be this exact value: if value is an object, each slot in the array will reference that object."](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#parameters) – Andy May 03 '23 at 21:22
  • or [How do I use array.fill for creating an array of objects?](https://stackoverflow.com/questions/50807131/how-do-i-use-array-fill-for-creating-an-array-of-objects) – pilchard May 03 '23 at 21:24
  • @Andy @pilchard just to make sure im following - so what is happening is that each of the indexes is referencing the same object created during fill, so each time I loop and update `audio`, I'm actually updating that same object that is referenced at each index? – Caleb Renfroe May 04 '23 at 17:30
  • 1
    That's correct @CalebRenfroe – Andy May 04 '23 at 18:38

0 Answers0