2 回答
TA贡献1786条经验 获得超11个赞
forEach忽略其回调返回的任何值。请改用for循环,以便return返回到 的调用者isValidNote,而不是被 忽略forEach:
const chromatic = ["A", "A#/Bb", "B/Cb", "B#/C", "C#/Db", "D", "D#/Eb", "E", "E#/Fb", "F", "F#/Gb", "G", "G#/Ab" ];
const isValidNote = (note)=> {
for (const item of chromatic) {
if(item.split("/").length > 1){
if(item.split("/")[0] == note) return true;
if(item.split("/")[1] == note) return true;
}
else if(item == note){
return true;
}
}
return false;
}
console.log(isValidNote("C"));
或者,更简洁地说:
const chromatic = ["A", "A#/Bb", "B/Cb", "B#/C", "C#/Db", "D", "D#/Eb", "E", "E#/Fb", "F", "F#/Gb", "G", "G#/Ab" ];
const isValidNote = (note)=> {
for (const item of chromatic) {
const allNotes = item.split("/");
if (allNotes.includes(note)) {
return true;
}
}
return false;
}
console.log(isValidNote("C"));
或者与.some:
const chromatic = ["A", "A#/Bb", "B/Cb", "B#/C", "C#/Db", "D", "D#/Eb", "E", "E#/Fb", "F", "F#/Gb", "G", "G#/Ab" ];
const isValidNote = note => chromatic.some(
item => item.split("/").includes(note)
);
console.log(isValidNote("C"));
TA贡献1796条经验 获得超10个赞
从forEach()回调返回只是继续循环,它不会从isValidNote()函数返回。
使用some()而不是forEach(). 如果任何回调返回 true,则它返回 true。
您还可以使用 来简化回调内的条件includes()。
const chromatic = ["A", "A#/Bb", "B/Cb", "B#/C", "C#/Db", "D", "D#/Eb", "E", "E#/Fb", "F", "F#/Gb", "G", "G#/Ab"];
const isValidNote = note => chromatic.some(item => item.split("/").includes(note));
console.log(isValidNote("C"));
添加回答
举报