javascript - 我的元素有一个值,直到将方法 .toLowerCase 附加到它

标签 javascript arrays

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

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: Cannot read property 'toLowerCase' of undefined

我不明白为什么。

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

最佳答案

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

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

相关文章:

python - 计算唯一 Python 数组区域之间的距离?

arrays - 如何知道字段是否是Elasticsearch中的数组?

javascript - 如何将当前日期移动到 jQuery 日期选择器日历的第一行

javascript - 我想在 HTML 元素中显示函数的返回值,但返回值是 NAN

javascript - 按钮在改变位置时不起作用

javascript - 在 Mocha 浏览器中使用多个记者?

javascript - 如何将javascript代码附加到asp.net中的这个动态控件文本框

php切割多维数组

java - 尝试比较两个数组并打印第一个数组的行(如果它们匹配)并为整个第一个数组循环它

c++ - Array[n] vs Array[10] - 使用变量初始化数组 vs 数值字面量