我试图将“ notes”键中的值更改为scale变量数组中的值。因此,运行该函数后,“注释”中的数字现在是var标度中的相应字母。例如:var chordArrays中的第一个“ notes”键值将读取为[d,f,a]而不是[1,3,5],依此类推。
var chordArrays = [
{
"chord type": "minor",
"inversion": "root",
"chords": [
{
"scale degree": "II",
"notes": [1,3,5]
},
{
"scale degree": "III",
"notes": [2,4,6]
},
{
"scale degree": "VI",
"notes": [5,0,2]
},
]
},
{
"chord type": "minor",
"inversion": "first",
"chords": [
{
"scale degree": "II",
"notes": [3,5,1]
},
{
"scale degree": "III",
"notes": [4,6,2]
},
{
"scale degree": "VI",
"notes": [0,2,5]
},
]
}]
var scale = [c,d,e,f,g,a,b]
function getMainChordsOfKey(scale,chordArrays) {
for (var i = 0; i < chordArrays.length; i++) {
for (var j = 0; j < chordArrays[i].chords.length; j++) {
for (var k = 0; k < chordArrays[i].chords[j].notes.length; k++) {
for (var z = 0; z < scale.length; z++) {
if (chordArrays[i].chords[j].notes[k] === z) {
replace k with z
}
}
}
}
}
};
答案 0 :(得分:0)
您的字母应该用引号分隔,否则JS不会将它们视为字符串,而是变量名。
这是您的方法:
const chordArrays = [{ "chord type": "minor", "inversion": "root", "chords": [ { "scale degree": "II", "notes": [1,3,5] }, { "scale degree": "III", "notes": [2,4,6] }, { "scale degree": "VI", "notes": [5,0,2] }, ] }, { "chord type": "minor", "inversion": "first", "chords": [ { "scale degree": "II", "notes": [3,5,1] }, { "scale degree": "III", "notes": [4,6,2] }, { "scale degree": "VI", "notes": [0,2,5] }, ] }]
const scale = "cdefgab"; // Can be array or string. But use quotes.
for (const type of chordArrays) {
for (const chord of type.chords) {
chord.notes = chord.notes.map(note => scale[note]);
}
}
console.log(chordArrays);
答案 1 :(得分:0)
看看这是否是您要寻找的
var chordArrays = [
{
'chord type': 'minor',
inversion: 'root',
chords: [
{
'scale degree': 'II',
notes: [1, 3, 5]
},
{
'scale degree': 'III',
notes: [2, 4, 6]
},
{
'scale degree': 'VI',
notes: [5, 0, 2]
}
]
},
{
'chord type': 'minor',
inversion: 'first',
chords: [
{
'scale degree': 'II',
notes: [3, 5, 1]
},
{
'scale degree': 'III',
notes: [4, 6, 2]
},
{
'scale degree': 'VI',
notes: [0, 2, 5]
}
]
}
];
var scale = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];
chordArrays.forEach(o => {
o.chords.forEach(n => {
n.notes = n.notes.map(i => (i = scale[i]));
});
});
console.log(chordArrays);
// sample on the DOM
document.querySelector('pre').innerHTML = chordArrays[0].chords[0].notes;
<pre></pre>
答案 2 :(得分:0)
这是一个不变的解决方案(不更改原始对象)
chordArrays.map(chord => ({
...chord,
chords: chord.chords.map(note => ({
...note,
notes: note.notes.map(note => scale[note])
}))
}))
->
[{
"chord type": "minor",
"inversion": "root",
"chords": [
{
"scale degree": "II",
"notes": [
"d",
"f",
"a"
]
}, ...]