我试图从数组中调用值,并让数组的名称由另一个变量中的字符串选择。假设我有两个数组。然后我想选择通过变量中的字符串从哪个数组中提取数据。
const notes = ['A','A#','B','C','C#','D','D#','E','F','F#','G','G#','A','A#','B','C','C#','D','D#','E','F','F#','G','G#','A'];
const minor = [0,2,3,5,7,8,10,12];
const major = [0,2,4,5,7,9,11,12];
let keyRoot = 5;
let keyScale = 'minor';
let output = "";
if (keyScale === 'minor'){
for(let i=0; i<8; i++){
let songKey = keyRoot -1 + minor[i]
output += notes[songKey]
output += ' '
}
}
console.log(output);
我想要做的就是删除 if 语句并使用变量 keyScale 调用数组 Minor 和 Major,因为 Scale 的数量可能会超过 Minor 和 Major,我觉得必须有一种比用 if 语句检查每种可能性。 keyScale和keyRoot将通过按钮在界面上设置。我仅在本示例中设置它们以获得输出。 所以我希望它看起来像这样
const notes = ['A','A#','B','C','C#','D','D#','E','F','F#','G','G#','A','A#','B','C','C#','D','D#','E','F','F#','G','G#','A'];
const minor = [0,2,3,5,7,8,10,12];
const major = [0,2,4,5,7,9,11,12];
let keyRoot = 5;
let keyScale = 'minor';
let output = "";
for(let i=0; i<8; i++){
let songKey = keyRoot -1 + keyScale[i]
output += notes[songKey]
output += ' '
}
console.log(output);
创建对象:
const arrays = {
minor,
major
}
获取数组:
arrays[keyScale]
const notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A'];
const minor = [0, 2, 3, 5, 7, 8, 10, 12];
const major = [0, 2, 4, 5, 7, 9, 11, 12];
const arrays = {
minor,
major
}
let keyRoot = 5;
let keyScale = 'minor';
let output = "";
for (let i = 0; i < 8; i++) {
let songKey = keyRoot - 1 + arrays[keyScale][i]
output += notes[songKey]
output += ' '
}
console.log(output);