gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:09:51 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com