javascript - 我的元素有一个值,直到将方法 .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];
};
解决方案
您的第一个对象没有属性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);
推荐阅读
- nlp - 需要一个“词袋”类型的变压器
- wordpress - 批量删除产品中的现有变体(wordpress woocommerce)
- firebase-realtime-database - 如果单个项目中有多个数据库,AngularFireAuth 无法发送 auth 对象并验证 RealtimeDatabase 的安全规则。角火
- python - python格式化f""操作符退出状态0
- python - Python重新查找组匹配的开始和结束索引
- django - Django Rest 框架 UnicodeDecodeError
- django - 数据库未显示在管理员上,给出模板错误“模型”没有属性用户
- python - 无法从自定义模块调用函数
- r - 在R包匹配中使用多个卡尺
- function - 通过函数返回本地存储的记录集