这是我的初始代码,可以完美运行。
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/