首页 > 解决方案 > 我的元素有一个值,直到将方法 .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 === 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];
};

标签: javascriptarrays

解决方案


您的第一个对象没有属性title,试图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);


推荐阅读