提问人:moe_reezy 提问时间:10/10/2023 更新时间:10/10/2023 访问量:34
如何通过 JavaScript 中的变量按名称调用多个数组之一?[复制]
How can I call one of multiple arrays by its name through a variable in JavaScript? [duplicate]
问:
我正在尝试从数组中调用值,并让数组的名称由另一个变量中的字符串选择。假设我有两个数组。然后,我想选择通过变量中的字符串从哪个数组中提取数据。
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,因为 Scales 的数量可能只会超过 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);
答:
0赞
Konrad
10/10/2023
#1
创建对象:
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);
评论
[keyScale]