这是我的初始代码,可以完美运行。



const objNotes = [
  {},
  {
    title: "Be better",
    body: "Do better"
  },
  {
    title: "You are what you eat",
    body: "Eat well and responsibly"
  },
  {
    title: "Look good",
    body: "Work good"
  }
];

const findNote = (notes, noteTitle) => {
  const index = notes.findIndex((note, index) => {
    return note.title === noteTitle;
  });
  return notes[index];
};

const action = findNote(objNotes, "Look good");
console.log(action);





当我像下面这样附加方法.toLowerCase时,我得到:


  TypeError:无法读取未定义的属性“ toLowerCase”


而且我不明白为什么。

const findNote = (notes, noteTitle) => {
  const index = notes.findIndex((note, index) => {
    return note.title.toLowerCase() === noteTitle.toLowerCase();
  });
  return notes[index];
};

最佳答案

您的第一个对象没有属性标题,试图向toLowerCase()抛出错误。

您可以在使用toLowerCase()之前检查对象中的属性是否存在:



const objNotes = [
  {},
  {
    title: "Be better",
    body: "Do better"
  },
  {
    title: "You are what you eat",
    body: "Eat well and responsibly"
  },
  {
    title: "Look good",
    body: "Work good"
  }
];

const findNote = (notes, noteTitle) => {
  const index = notes.findIndex((note, index) => {
    return note.title == undefined? '' : note.title.toLowerCase() === noteTitle.toLowerCase();
  });
  return notes[index];
};

const action = findNote(objNotes, "Look good");
console.log(action);

关于javascript - 我的元素具有一个值,直到将方法.toLowerCase附加到它为止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59978023/

10-09 15:51