2 回答

TA貢獻1877條經(jīng)驗 獲得超1個贊
由于您沒有提供錯誤日志,我只能猜測出了什么問題:您RefernceError
在回調(diào)中有一個。如果是這種情況,原因如下:
const notes = [ {},{
請注意,您在數(shù)組中有一個空對象notes
,并且title
在item.title.toUpperCase()
評估undefined
導(dǎo)致 a 的原因ReferenceError
時,只需刪除空對象即可解決此問題。
它沒有工作的原因toUpperCase
是因為沒有取消引用title
,你只是在它上面使用 === 并不關(guān)心它是否是undefined
.

TA貢獻1845條經(jīng)驗 獲得超8個贊
您可以添加檢查您的notes數(shù)組對象是否具有屬性title??梢允褂胔asOwnProperty檢查:
if (fooObject.hasOwnProperty('title'))
或者在你的情況下:
item.hasOwnProperty('title')
但是,我們希望找到titlekey 不存在的情況并省略這些對象,因為如果不存在title,則意味著沒有方法toUpperCase()。所以可以用運算符!(NOT)檢查:
if (!item.title) // `NOT` + undefined gives `true`
return false;
所以整個代碼看起來像這樣:
const notes = [
{},
{
title: 'My next trip',
body: 'I would like to go to Spain'
},
{
title: 'Habbits to work on',
body: 'Excercise, Eat a bit better'
},
{
title: 'Office modification',
body: 'Get a new seat'
}
]
function findNote(notes, noteTitle) {
const index = notes.findIndex(function (item, index) {
if (!item.title)
return false;
return item.title.toUpperCase() === noteTitle.toUpperCase()
})
return notes[index]
}
const note = findNote(notes, 'Office modification')
console.log(note)
添加回答
舉報