The alltones array contains all the possible notes in music scale.
var alltones = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ];
I want to take the user’s input of a tone, and then construct a list that contains certain elements of the array.
Say I start at alltones[5] or "F", and want to take every second element of the array from that point and put it into my list, until I get back around to "F". The array is more like a circle than straight list. I’m a little unsure of how the array operates once the loop reaches the last element.
Do I approach the problem by generating a new array, based on the users input. Or is there a way that JavaScript knows to loop back to the start of an array once it reaches the end such that it treats the array like a circle?
An example:
User input = F
The output that I am seeking is to count (every two items) from F until we get back around the array to F
so the desired output would be => F G A B C# D#
There isn’t an existing Array method to do what you want, but one is easily defined using
Array.prototype.sliceandArray.prototype.concat:And then you can use
lcycleandrcycleas normal array methods:Note that both of these methods return a new array. If you wanted to mutate the original array, you could define similar methods using
Array.prototype.splice.And again, you can can use
lcycle_mandrcycle_mas normal array methods: