I have an array in JavaScript containing music notes:
const musicNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
The user will select a note from an HTML select list, and the selected value will be stored in a variable tonalityNote
.
This tonalityNote
will then be passed to a function like this:
getThirdDegreeNote(tonalityNote) {
/* Get the index of tonalityNote in the musicNotes array */
const tonalityNoteIndex = musicNotes.indexOf(tonalityNote);
/* Get the value at the index tonalityNoteIndex + 2 in the musicNotes array */
return musicNotes[tonalityNoteIndex + 4];
}
If tonalityNote
is 'C' (the first element of the musicNotes array), there's no issue - it will always work.
However, if tonalityNote
is 'B', the formula
musicNotes[tonalityNoteIndex + 4]
will return undefined.
Is there a way to wrap around to the beginning of the array when encountering such issues?
For instance, if I'm at the index with the value 'B' in the musicNotes
array, can I ensure that
return musicNotes[tonalityNoteIndex + 4]
will actually return 'D#' (considering the array 'musicNotes' and counting + 4 from 'B' for clarity)?
I hope I have explained the problem clearly. This is causing me quite some struggle.
Thank you in advance.