为了账号安全,请及时绑定邮箱和手机立即绑定

JavaScript“If 语句”不返回真值

JavaScript“If 语句”不返回真值

潇潇雨雨 2023-08-24 10:36:45
我编写了一个简单的函数,通过循环数组并比较值来检查提供的注释是否有效。代码总是返回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"));
查看完整描述

2 回答

?
Qyouu

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


查看完整回答
反对 回复 2023-08-24
?
白衣染霜花

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


查看完整回答
反对 回复 2023-08-24
  • 2 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信