JavaScript“If 语句”不返回真值

我编写了一个简单的函数,通过循环数组并比较值来检查提供的注释是否有效。


代码总是返回false,我不确定为什么?


item.split("/")[1] == note当我单独运行代码时,它会返回true(带有 note = "C" ),那么为什么我的函数总是返回false?


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.forEach((item) => {

    if (item.split("/").length > 1) {


      console.log(item.split("/")[1] == note); // logs true on 3rd iteration


      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"));


潇潇雨雨
浏览 187回答 2
2回答

Qyouu

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"));

白衣染霜花

从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"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript