We should take a moment here and make sure @atagger understands the concept of a reference. When you create an array and assign values to it as you do with bandsEnergy
, when you use that array, passing it to a function, or adding it to another array/data structure, you are adding a reference to the original array. That means that if you change the array later, those changes will be reflected in all the places that reference the original array.
The slice()
function is a common way to make a quick copy of an array. The original will not be modified, and the array returned by slice()
will be a brand new array that contains the same values (note: don’t confuse slice with splice, they are very different). So specifically in the context of your code:
// this will add a reference to bandsEnergy, and if you change bandsEnergy later
// those changes will be reflected by each reference to that one array, which is
// why you would end up with an array of 32 identical arrays containing just the
// latest value
sampleBuffer.push(bandsEnergy);
// This, on the other hand, will make a copy of bandsEnergy and should achieve
// your desired behavior
sampleBuffer.push(bandsEnergy.slice());
// Note that slice takes two parameters, a start index and a length, and returns
// just that range of the array. However both of these parameters are optional.
There are other ways to solve this issue:
- The spread operator
// The array initialize with the spread operator:
sampleBuffer.push([...bandsEnergy]);
- Make bandsEnergy a local variable and initialize it to a new array
bandsEnergy = []
in each call to draw.