简体   繁体   中英

JavaScript: TypeError cant read property 'toLowerCase' of undefined?

I am getting error while running this code , it's saying typeerror cant read property to 'lowercase' of undefined. Code:-

 const notes = [{},{ title: "My next Trip", body: "I would like to go to USA" },{ title: "Habbits to work on", body: "Exercise" } ,{ title: "Office Modification", body: "Get a new seat" } ] const findNote = function(notes, noteTitle) { const index = notes.findIndex(function (note , index) { return note.title.toLowercase() === noteTitle.toLowerCase() }) return notes[index] } const note = findNote(notes, "Office Modification") console.log(note);

There are 2 errors in the code

  • Javascript is case sensitive - the correct function is toLowerCase
  • There is an empty object which does not have title property - you need to add safe check for that in code

You can try following

 const notes = [{},{ title: "My next Trip", body: "I would like to go to USA" },{ title: "Habbits to work on", body: "Exercise" } ,{ title: "Office Modification", body: "Get a new seat" } ] const findNote = function(notes, noteTitle) { const index = notes.findIndex(function (note , index) { return note.title && note.title.toLowerCase() === noteTitle.toLowerCase() }) return notes[index] } const note = findNote(notes, "Office Modification") console.log(note);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM